Leetcode——94.二叉树的中序遍历

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

示例:

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

2
/
3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

思路:就用非递归来写,先一股脑把左边一条线全部push到底(即走到最左边),然后node最终为None了就开始pop stack了,然后因为pop出来的每一个node都是自己这棵树的root,所以看看它有没有右孩子,没有那肯定继续pop,有的话自然而然右孩子是下一个要被访问的节点。

Leetcode——94.二叉树的中序遍历

class Solution:
    def inorderTraversal(self, root: 'TreeNode') -> 'List[int]':
        if not root:
            return []
        stack = []
        node = root
        res = []
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            res.append(node.val)
            node = node.right
        return res