94. Binary Tree Inorder Traversal 二叉树的中序遍历

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

示例:

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

输出: [1,3,2]

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

二叉树遍历

不太想用递归,试试循环吧。

Code

    def inorderTraversal(self, root: TreeNode) -> List[int]:
        ans = []
        if root is not None:
            stack, temp = [], root
            while stack or temp is not None:
                if temp is not None:
                    stack.append(temp)
                    temp = temp.left
                else:
                    temp = stack.pop()
                    ans.append(temp.val)
                    temp = temp.right
        return ans

猜你喜欢

转载自blog.csdn.net/weixin_43336281/article/details/108571725