给定一个二叉树,返回它的 前中后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
思路
直接递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
l = []
def pre(ro):
nonlocal l
if ro:
l.append(ro.val)
pre(ro.left)
pre(ro.right)
else:
return
pre(root)
return l
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
l = []
def pre(ro):
nonlocal l
if ro:
pre(ro.left)
l.append(ro.val)
pre(ro.right)
else:
return
pre(root)
return l
迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
l = []
if not root:
return l
stack = [root]
while stack:
tmp = stack.pop()
l.append(tmp.val)
if tmp.right:
stack.append(tmp.right)
if tmp.left:
stack.append(tmp.left)
return l
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
stack = []
res = []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
res.append(root.val)
root = root.right
return res
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = [] # 用来存储后序遍历节点的值
stack = []
node = root
while stack or node:
while node:
stack.append(node) # 第一次入栈的是根节点
#判断当前节点的左子树是否存在,若存在则持续左下行,若不存在就转向右子树
node = node.left if node.left is not None else node.right
#循环结束说明走到了叶子节点,没有左右子树了,该叶子节点即为当前栈顶元素,应该访问了
node = stack.pop() # 取出栈顶元素进行访问
res.append(node.val) # 将栈顶元素也即当前节点的值添加进res
# (下面的stack[-1]是执行完上面那句取出栈顶元素后的栈顶元素)
if stack and stack[-1].left == node: #若栈不为空且当前节点是栈顶元素的左节点
node = stack[-1].right ## 则转向遍历右节点
else:
node = None # 没有左子树或右子树,强迫退栈
return res