题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
链接:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
描述:二叉树的后序遍历,非递归
solution by python:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def postorderTraversal(self, root):
if not root: return []
stk,ans = [root,],[]
pre = root
while len(stk) != 0:
p = stk[-1]
if p.left==None and p.right==None or (p.left==pre or p.right==pre):
ans.append(p.val)
pre = stk.pop()
else:
if p.right != None: stk.append(p.right)
if p.left != None: stk.append(p.left)
return ans