lc 145. Binary Tree Postorder Traversal

https://leetcode.com/problems/binary-tree-postorder-traversal/description/

不用递归的方式进行树的后序遍历

思路就是当前的根我们可以确定是最后的,我们就放入结果数组。然后他的左儿子不一定什么时候放,视右儿子数量决定,就把左儿子放入等待数组,以上用一个小函数去执行。

循环终止条件就是等待数组为空。

以上完成了一个倒置的后序遍历,把结果数组倒置回来就ok。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def __init__(self):
        self.ans=[]
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        todo=[root]
        while len(todo)>0:
            if todo[-1]==None:
                todo.pop()
                continue
            self.ans.append(todo[-1].val)
            node=todo.pop()
            todo.append(node.left)
            todo.append(node.right)
        return list(reversed(self.ans))
View Code

猜你喜欢

转载自www.cnblogs.com/waldenlake/p/9626649.html