给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack=Stack()
result=[]
if not root:
return result
stack.push(root)
#每次先压入右子树 然后压入左子树
while not stack.isEmpty() :
root=stack.pop()
result.append(root.val)
if root.right:
stack.push(root.right)
if root.left:
stack.push(root.left)
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