题目描述
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
我的解法——递归(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 [tree.val, ] + left + right
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
return self.getpre(root)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
我的解法——非递归(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 go_left(self, res, stack, now):
while(now):
res.append(now.val)
stack.append(now)
now = now.left
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
res = []
now = root
while(now):
self.go_left(res, stack, now)
while(True):
if(not len(stack)):
now = None
break
if(stack[-1].right):
now = stack[-1].right
stack = stack[: -1]
break
else:
stack = stack[: -1]
return res