6 - Medium - 中序遍历二叉树

2018-06-11  本文已影响0人  1f872d1e3817

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

示例:

输入: [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
上一篇 下一篇

猜你喜欢

热点阅读