美文网首页
6 - Medium - 中序遍历二叉树

6 - Medium - 中序遍历二叉树

作者: 1f872d1e3817 | 来源:发表于2018-06-11 16:05 被阅读0次

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

递归

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        
        return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right)

循环

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        l = []
        node_l = []
        left = root
        while True:
            if left:
                node_l.append(left)
                left = left.left
            elif node_l:
                node = node_l.pop()
                l.append(node.val)
                left = node.right
            else:
                break
        return l

相关文章

网友评论

      本文标题:6 - Medium - 中序遍历二叉树

      本文链接:https://www.haomeiwen.com/subject/yqeheftx.html