给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
#145. 二叉树的后序遍历
class Solution(object):
#非递归实现后续遍历
#准备两个栈 第一个栈先遍历根节点 然后将左子树和右子树压入栈 每次遍历到的节点都放入栈二
#栈二最后的结果就是后续遍历的结果
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
#使用两个栈
result=[]
if not root:
return result
stack1=Stack()
stack2 = Stack()
stack1.push(root)
while not stack1.isEmpty():
node=stack1.pop()
if node.left:
stack1.push(node.left)
if node.right:
stack1.push(node.right)
stack2.push(node)
while not stack2.isEmpty():
node=stack2.pop()
result.append(node.val)
return result
class Stack(object):
def __init__(self):
self.index=-1
self.arr=[]
def push(self,value):
self.arr.append(value)
self.index+=1
def isEmpty(self):
if self.index>=0:
return False
return True
def pop(self):
if self.isEmpty():
return
temp=self.arr[self.index]
self.arr.pop(-1)
self.index-=1
return temp