LeetCode94:Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?


LeetCode:链接

二叉树的中序遍历。

1)递归实现:

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

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]
        """
        res, stack = [], []
        while root or stack:
            if root:
                stack.append(root)
                # 遍历左子树
                root = root.left
            else:
                node = stack.pop()
                # 根节点
                res.append(node.val)
                # 右子树
                root = node.right
        return res

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/85780630