94. Binary Tree Inorder Traversal Binary Tree Inorder Traversal

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

Example:

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

Advanced: The  recursive algorithm is very simple, can you do it through an iterative algorithm?

Binary tree traversal

Don't want to use recursion, try looping.

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

Guess you like

Origin blog.csdn.net/weixin_43336281/article/details/108571725