递归遍历二叉树:
Python:(拼接子树返回的列表和[root.val])
# 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# 终止条件
if not root:
return []
# 递归左右子树
left = self.preorderTraversal(root.left)
right = self.preorderTraversal(root.right)
# 递归函数的返回值
return [root.val] + left + right
# 后序遍历
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# 终止条件
if not root:
return []
# 递归左右子树
left = self.postorderTraversal(root.left)
right = self.postorderTraversal(root.right)
# 递归函数的返回值
return left + right + [root.val]
# 中序遍历
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# 终止条件
if not root:
return []
# 递归左右子树
left = self.inorderTraversal(root.left)
right = self.inorderTraversal(root.right)
# 递归函数的返回值
return left + [root.val] + right
Java:(修改ans列表)
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// define ans
List<Integer> ans = new ArrayList<Integer>();
preorder(root, ans);
return ans;
}
public void preorder(TreeNode root, List<Integer> ans){
// stop condition
if (root == null){
return;
}
// Each step of recurion
ans.add(root.val);
preorder(root.left, ans);
preorder(root.right, ans);
}
}
迭代遍历二叉树:
Python
# 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# stop condition
if not root:
return []
# stack
stack = []
# answer
ans = []
# initial stack
stack.append(root)
while stack:
# Forst, process the root node
root = stack[-1]
ans.append(stack[-1].val)
stack.pop()
# Then, pull right tree and left tree which to be process
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
return ans
# 后序遍历:前序遍历入栈顺序变为先左再右,最后输出倒序的结果
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# stop condition
if not root:
return []
# stack
stack = []
# answer
ans = []
# initial stack
stack.append(root)
while stack:
# Forst, process the root node
root = stack[-1]
ans.append(stack[-1].val)
stack.pop()
# Then, pull right tree and left tree which to be process
if root.right:
stack.append(root.left)
if root.left:
stack.append(root.right)
return ans[::-1]
# 中序遍历
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
stack = [] # The root node cannot be added to stack early
ans = []
cur = root
while cur or stack:
# Iterate over the lowest left subtree element first
if cur:
stack.append(cur)
cur = cur.left
# process the top of the stack after reaching the leftmost node
else:
cur = stack.pop()
ans.append(cur.val)
# Take the right element of the top element of the stack
cur = cur.right
return ans