题目描述
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
我的解法——递归(AC)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getpre(self, tree):
if(not tree):
return []
left = self.getpre(tree.left)
right = self.getpre(tree.right)
return left + right + [tree.val, ]
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
return self.getpre(root)
我的解法——双栈非递归(AC)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if(not root):
return []
s1 = [root, ]
s2 = []
while(len(s1)):
now = s1[-1]
s2.append(s1[-1].val)
s1 = s1[:-1]
if(now.left):
s1.append(now.left)
if(now.right):
s1.append(now.right)
return s2[::-1]
我的解法——单栈非递归
- 见《程序员代码面试指南》P92