1. 程式人生 > >lc 145. Binary Tree Postorder Traversal

lc 145. Binary Tree Postorder Traversal

self int div right .com close spl open 思路

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

lc 145. Binary Tree Postorder Traversal