144. 二叉树的前序遍历
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
result = []
stack = [root]
# 需要一个标志区分每个递归调用栈,这里使用null来表示
while stack:
p = stack.pop() # 访问过的节点弹出
if p is None: # 空节点表示之前已经访问过了,现在需要处理除了递归之外的内容
p = stack.pop() # 处理完了,第二次弹出节点(彻底从栈中移除)
result.append(p.val) # 此时p是null之前压栈的一个节点,也就是上面stack.append(p)中的那个p
else:
if p.right: # 右节点先压栈,最后处理
stack.append(p.right) # 先append的最后访问
if p.left:
stack.append(p.left)
stack.append(p) # 当前节点重新压栈(留着以后处理),因为先序遍历所以最后压栈
stack.append(None) # 在当前节点之前加入一个空节点表示已经访问过了
return result
94. 二叉树的中序遍历
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
# 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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
result = []
stack = [root]
# 需要一个标志区分每个递归调用栈,这里使用null来表示
while stack:
p = stack.pop() # 访问过的节点弹出
if p is None: # 空节点表示之前已经访问过了,现在需要处理除了递归之外的内容
p = stack.pop() # 处理完了,第二次弹出节点(彻底从栈中移除)
result.append(p.val) # 此时p是null之前压栈的一个节点,也就是上面stack.append(p)中的那个p
else:
if p.right: # 右节点先压栈,最后处理
stack.append(p.right) # 先append的最后访问
stack.append(p) # 当前节点重新压栈(留着以后处理),因为先序遍历所以最后压栈
stack.append(None) # 在当前节点之前加入一个空节点表示已经访问过了
if p.left:
stack.append(p.left)
return result
145. 二叉树的后序遍历
https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
# 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 root is None:
return []
result = []
stack = [root]
# 需要一个标志区分每个递归调用栈,这里使用null来表示
while stack:
p = stack.pop() # 访问过的节点弹出
if p is None: # 空节点表示之前已经访问过了,现在需要处理除了递归之外的内容
p = stack.pop() # 处理完了,第二次弹出节点(彻底从栈中移除)
result.append(p.val) # 此时p是null之前压栈的一个节点,也就是上面stack.append(p)中的那个p
else:
stack.append(p) # 当前节点重新压栈(留着以后处理),因为先序遍历所以最后压栈
stack.append(None) # 在当前节点之前加入一个空节点表示已经访问过了
if p.right: # 右节点先压栈,最后处理
stack.append(p.right) # 先append的最后访问
if p.left:
stack.append(p.left)
return result
参考题解