7.2 二叉树遍历¶
从物理结构的角度来看,树是一种基于链表的数据结构,因此其遍历方式是通过指针逐个访问节点。然而,树是一种非线性数据结构,这使得遍历树比遍历链表更加复杂,需要借助搜索算法来实现。
二叉树常见的遍历方式包括层序遍历、前序遍历、中序遍历和后序遍历等。
7.2.1 层序遍历¶
如图 7-9 所示,层序遍历(level-order traversal)从顶部到底部逐层遍历二叉树,并在每一层按照从左到右的顺序访问节点。
层序遍历本质上属于广度优先遍历(breadth-first traversal),也称广度优先搜索(breadth-first search, BFS),它体现了一种“一圈一圈向外扩展”的逐层遍历方式。
图 7-9 二叉树的层序遍历
图解 7-9:二叉树的层序遍历
按从顶层到底层、同一层内从左到右的次序逐层访问二叉树节点。
示例二叉树共三层 7 个节点:根节点为 1;1 的左、右子节点分别为 2、3;2 的左、右子节点分别为 4、5;3 的左、右子节点分别为 6、7。其中 4、5、6、7 为叶节点。
| 层 | 从左到右的节点 |
|---|---|
| 1 | 1 |
| 2 | 2、3 |
| 3 | 4、5、6、7 |
第 2 层的 2、3 访问完毕后,转入第 3 层最左侧的节点 4,所以访问 3 之后是 4。灰色实线箭头表示父子关系;经过节点底部蓝点的虚线箭头只表示访问先后。因此 3→4 的斜向虚线是跨层访问路径,4 的父节点仍是 2。
层序遍历序列为 [1, 2, 3, 4, 5, 6, 7],每个节点恰好访问一次。
1. 代码实现¶
广度优先遍历通常借助“队列”来实现。队列遵循“先进先出”的规则,而广度优先遍历则遵循“逐层推进”的规则,两者背后的思想是一致的。实现代码如下:
def level_order(root: TreeNode | None) -> list[int]:
"""层序遍历"""
# 初始化队列,加入根节点
queue: deque[TreeNode] = deque()
queue.append(root)
# 初始化一个列表,用于保存遍历序列
res = []
while queue:
node: TreeNode = queue.popleft() # 队列出队
res.append(node.val) # 保存节点值
if node.left is not None:
queue.append(node.left) # 左子节点入队
if node.right is not None:
queue.append(node.right) # 右子节点入队
return res
/* 层序遍历 */
vector<int> levelOrder(TreeNode *root) {
// 初始化队列,加入根节点
queue<TreeNode *> queue;
queue.push(root);
// 初始化一个列表,用于保存遍历序列
vector<int> vec;
while (!queue.empty()) {
TreeNode *node = queue.front();
queue.pop(); // 队列出队
vec.push_back(node->val); // 保存节点值
if (node->left != nullptr)
queue.push(node->left); // 左子节点入队
if (node->right != nullptr)
queue.push(node->right); // 右子节点入队
}
return vec;
}
/* 层序遍历 */
List<Integer> levelOrder(TreeNode root) {
// 初始化队列,加入根节点
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// 初始化一个列表,用于保存遍历序列
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // 队列出队
list.add(node.val); // 保存节点值
if (node.left != null)
queue.offer(node.left); // 左子节点入队
if (node.right != null)
queue.offer(node.right); // 右子节点入队
}
return list;
}
/* 层序遍历 */
List<int> LevelOrder(TreeNode root) {
// 初始化队列,加入根节点
Queue<TreeNode> queue = new();
queue.Enqueue(root);
// 初始化一个列表,用于保存遍历序列
List<int> list = [];
while (queue.Count != 0) {
TreeNode node = queue.Dequeue(); // 队列出队
list.Add(node.val!.Value); // 保存节点值
if (node.left != null)
queue.Enqueue(node.left); // 左子节点入队
if (node.right != null)
queue.Enqueue(node.right); // 右子节点入队
}
return list;
}
/* 层序遍历 */
func levelOrder(root *TreeNode) []any {
// 初始化队列,加入根节点
queue := list.New()
queue.PushBack(root)
// 初始化一个切片,用于保存遍历序列
nums := make([]any, 0)
for queue.Len() > 0 {
// 队列出队
node := queue.Remove(queue.Front()).(*TreeNode)
// 保存节点值
nums = append(nums, node.Val)
if node.Left != nil {
// 左子节点入队
queue.PushBack(node.Left)
}
if node.Right != nil {
// 右子节点入队
queue.PushBack(node.Right)
}
}
return nums
}
/* 层序遍历 */
func levelOrder(root: TreeNode) -> [Int] {
// 初始化队列,加入根节点
var queue: [TreeNode] = [root]
// 初始化一个列表,用于保存遍历序列
var list: [Int] = []
while !queue.isEmpty {
let node = queue.removeFirst() // 队列出队
list.append(node.val) // 保存节点值
if let left = node.left {
queue.append(left) // 左子节点入队
}
if let right = node.right {
queue.append(right) // 右子节点入队
}
}
return list
}
/* 层序遍历 */
function levelOrder(root) {
// 初始化队列,加入根节点
const queue = [root];
// 初始化一个列表,用于保存遍历序列
const list = [];
while (queue.length) {
let node = queue.shift(); // 队列出队
list.push(node.val); // 保存节点值
if (node.left) queue.push(node.left); // 左子节点入队
if (node.right) queue.push(node.right); // 右子节点入队
}
return list;
}
/* 层序遍历 */
function levelOrder(root: TreeNode | null): number[] {
// 初始化队列,加入根节点
const queue = [root];
// 初始化一个列表,用于保存遍历序列
const list: number[] = [];
while (queue.length) {
let node = queue.shift() as TreeNode; // 队列出队
list.push(node.val); // 保存节点值
if (node.left) {
queue.push(node.left); // 左子节点入队
}
if (node.right) {
queue.push(node.right); // 右子节点入队
}
}
return list;
}
/* 层序遍历 */
List<int> levelOrder(TreeNode? root) {
// 初始化队列,加入根节点
Queue<TreeNode?> queue = Queue();
queue.add(root);
// 初始化一个列表,用于保存遍历序列
List<int> res = [];
while (queue.isNotEmpty) {
TreeNode? node = queue.removeFirst(); // 队列出队
res.add(node!.val); // 保存节点值
if (node.left != null) queue.add(node.left); // 左子节点入队
if (node.right != null) queue.add(node.right); // 右子节点入队
}
return res;
}
/* 层序遍历 */
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
// 初始化队列,加入根节点
let mut que = VecDeque::new();
que.push_back(root.clone());
// 初始化一个列表,用于保存遍历序列
let mut vec = Vec::new();
while let Some(node) = que.pop_front() {
// 队列出队
vec.push(node.borrow().val); // 保存节点值
if let Some(left) = node.borrow().left.as_ref() {
que.push_back(left.clone()); // 左子节点入队
}
if let Some(right) = node.borrow().right.as_ref() {
que.push_back(right.clone()); // 右子节点入队
};
}
vec
}
/* 层序遍历 */
int *levelOrder(TreeNode *root, int *size) {
/* 辅助队列 */
int front, rear;
int index, *arr;
TreeNode *node;
TreeNode **queue;
/* 辅助队列 */
queue = (TreeNode **)malloc(sizeof(TreeNode *) * MAX_SIZE);
// 队列指针
front = 0, rear = 0;
// 加入根节点
queue[rear++] = root;
// 初始化一个列表,用于保存遍历序列
/* 辅助数组 */
arr = (int *)malloc(sizeof(int) * MAX_SIZE);
// 数组指针
index = 0;
while (front < rear) {
// 队列出队
node = queue[front++];
// 保存节点值
arr[index++] = node->val;
if (node->left != NULL) {
// 左子节点入队
queue[rear++] = node->left;
}
if (node->right != NULL) {
// 右子节点入队
queue[rear++] = node->right;
}
}
// 更新数组长度的值
*size = index;
arr = realloc(arr, sizeof(int) * (*size));
// 释放辅助数组空间
free(queue);
return arr;
}
/* 层序遍历 */
fun levelOrder(root: TreeNode?): MutableList<Int> {
// 初始化队列,加入根节点
val queue = LinkedList<TreeNode?>()
queue.add(root)
// 初始化一个列表,用于保存遍历序列
val list = mutableListOf<Int>()
while (queue.isNotEmpty()) {
val node = queue.poll() // 队列出队
list.add(node?._val!!) // 保存节点值
if (node.left != null)
queue.offer(node.left) // 左子节点入队
if (node.right != null)
queue.offer(node.right) // 右子节点入队
}
return list
}
可视化运行
2. 复杂度分析¶
- 时间复杂度为 \(O(n)\) :所有节点被访问一次,使用 \(O(n)\) 时间,其中 \(n\) 为节点数量。
- 空间复杂度为 \(O(n)\) :在最差情况下,即满二叉树时,遍历到最底层之前,队列中最多同时存在 \((n + 1) / 2\) 个节点,占用 \(O(n)\) 空间。
7.2.2 前序、中序、后序遍历¶
相应地,前序、中序和后序遍历都属于深度优先遍历(depth-first traversal),也称深度优先搜索(depth-first search, DFS),它体现了一种“先走到尽头,再回溯继续”的遍历方式。
图 7-10 展示了对二叉树进行深度优先遍历的工作原理。深度优先遍历就像是绕着整棵二叉树的外围“走”一圈,在每个节点都会遇到三个位置,分别对应前序遍历、中序遍历和后序遍历。
图 7-10 二叉搜索树的前序、中序、后序遍历
图解 7-10:二叉树的三种深度优先遍历
沿同一深度优先递归轨迹,按记录当前节点值的时机区分前序、中序与后序遍历。
图注写作“二叉搜索树”,但图中实际是普通二叉树:根 1 的左子节点为 2,大于根值,不满足搜索树的左小右大关系。因此这里的中序输出并非升序。
树共 7 个节点:根为 1,1 的左、右子节点是 2、3,2 的左、右子节点是 4、5,3 的左、右子节点是 6、7;4、5、6、7 为叶节点。
环绕树的虚线表示递归调用与返回的深度优先轨迹,并非父子边。每个节点左侧的橙点对应前序(左递归前),下方的蓝点对应中序(左右递归之间),右侧的紫点对应后序(右递归后)。
三种遍历都先递归处理左子树,再递归处理右子树,遇到空节点即返回;差别是何时记录当前节点。下表列出三种记录时机、访问优先级及各自输出。
| 遍历 | 记录当前节点的时机 | 访问优先级 | 输出序列 |
|---|---|---|---|
| 前序 | 左递归之前 | 根 → 左子树 → 右子树 | 1, 2, 4, 5, 3, 6, 7 |
| 中序 | 左递归之后、右递归之前 | 左子树 → 根 → 右子树 | 4, 2, 5, 1, 6, 3, 7 |
| 后序 | 右递归之后 | 左子树 → 右子树 → 根 | 4, 5, 2, 6, 7, 3, 1 |
1. 代码实现¶
深度优先搜索通常基于递归实现:
def pre_order(root: TreeNode | None):
"""前序遍历"""
if root is None:
return
# 访问优先级:根节点 -> 左子树 -> 右子树
res.append(root.val)
pre_order(root=root.left)
pre_order(root=root.right)
def in_order(root: TreeNode | None):
"""中序遍历"""
if root is None:
return
# 访问优先级:左子树 -> 根节点 -> 右子树
in_order(root=root.left)
res.append(root.val)
in_order(root=root.right)
def post_order(root: TreeNode | None):
"""后序遍历"""
if root is None:
return
# 访问优先级:左子树 -> 右子树 -> 根节点
post_order(root=root.left)
post_order(root=root.right)
res.append(root.val)
/* 前序遍历 */
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
// 访问优先级:根节点 -> 左子树 -> 右子树
vec.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
/* 中序遍历 */
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root->left);
vec.push_back(root->val);
inOrder(root->right);
}
/* 后序遍历 */
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root->left);
postOrder(root->right);
vec.push_back(root->val);
}
/* 前序遍历 */
void preOrder(TreeNode root) {
if (root == null)
return;
// 访问优先级:根节点 -> 左子树 -> 右子树
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* 中序遍历 */
void inOrder(TreeNode root) {
if (root == null)
return;
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
/* 后序遍历 */
void postOrder(TreeNode root) {
if (root == null)
return;
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}
/* 前序遍历 */
void PreOrder(TreeNode? root) {
if (root == null) return;
// 访问优先级:根节点 -> 左子树 -> 右子树
list.Add(root.val!.Value);
PreOrder(root.left);
PreOrder(root.right);
}
/* 中序遍历 */
void InOrder(TreeNode? root) {
if (root == null) return;
// 访问优先级:左子树 -> 根节点 -> 右子树
InOrder(root.left);
list.Add(root.val!.Value);
InOrder(root.right);
}
/* 后序遍历 */
void PostOrder(TreeNode? root) {
if (root == null) return;
// 访问优先级:左子树 -> 右子树 -> 根节点
PostOrder(root.left);
PostOrder(root.right);
list.Add(root.val!.Value);
}
/* 前序遍历 */
func preOrder(node *TreeNode) {
if node == nil {
return
}
// 访问优先级:根节点 -> 左子树 -> 右子树
nums = append(nums, node.Val)
preOrder(node.Left)
preOrder(node.Right)
}
/* 中序遍历 */
func inOrder(node *TreeNode) {
if node == nil {
return
}
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(node.Left)
nums = append(nums, node.Val)
inOrder(node.Right)
}
/* 后序遍历 */
func postOrder(node *TreeNode) {
if node == nil {
return
}
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(node.Left)
postOrder(node.Right)
nums = append(nums, node.Val)
}
/* 前序遍历 */
func preOrder(root: TreeNode?) {
guard let root = root else {
return
}
// 访问优先级:根节点 -> 左子树 -> 右子树
list.append(root.val)
preOrder(root: root.left)
preOrder(root: root.right)
}
/* 中序遍历 */
func inOrder(root: TreeNode?) {
guard let root = root else {
return
}
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root: root.left)
list.append(root.val)
inOrder(root: root.right)
}
/* 后序遍历 */
func postOrder(root: TreeNode?) {
guard let root = root else {
return
}
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root: root.left)
postOrder(root: root.right)
list.append(root.val)
}
/* 前序遍历 */
function preOrder(root) {
if (root === null) return;
// 访问优先级:根节点 -> 左子树 -> 右子树
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* 中序遍历 */
function inOrder(root) {
if (root === null) return;
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
/* 后序遍历 */
function postOrder(root) {
if (root === null) return;
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
/* 前序遍历 */
function preOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// 访问优先级:根节点 -> 左子树 -> 右子树
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* 中序遍历 */
function inOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
/* 后序遍历 */
function postOrder(root: TreeNode | null): void {
if (root === null) {
return;
}
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
/* 前序遍历 */
void preOrder(TreeNode? node) {
if (node == null) return;
// 访问优先级:根节点 -> 左子树 -> 右子树
list.add(node.val);
preOrder(node.left);
preOrder(node.right);
}
/* 中序遍历 */
void inOrder(TreeNode? node) {
if (node == null) return;
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(node.left);
list.add(node.val);
inOrder(node.right);
}
/* 后序遍历 */
void postOrder(TreeNode? node) {
if (node == null) return;
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(node.left);
postOrder(node.right);
list.add(node.val);
}
/* 前序遍历 */
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// 访问优先级:根节点 -> 左子树 -> 右子树
let node = node.borrow();
res.push(node.val);
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* 中序遍历 */
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// 访问优先级:左子树 -> 根节点 -> 右子树
let node = node.borrow();
dfs(node.left.as_ref(), res);
res.push(node.val);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* 后序遍历 */
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// 访问优先级:左子树 -> 右子树 -> 根节点
let node = node.borrow();
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
res.push(node.val);
}
}
dfs(root, &mut result);
result
}
/* 前序遍历 */
void preOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// 访问优先级:根节点 -> 左子树 -> 右子树
arr[(*size)++] = root->val;
preOrder(root->left, size);
preOrder(root->right, size);
}
/* 中序遍历 */
void inOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root->left, size);
arr[(*size)++] = root->val;
inOrder(root->right, size);
}
/* 后序遍历 */
void postOrder(TreeNode *root, int *size) {
if (root == NULL)
return;
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root->left, size);
postOrder(root->right, size);
arr[(*size)++] = root->val;
}
/* 前序遍历 */
fun preOrder(root: TreeNode?) {
if (root == null) return
// 访问优先级:根节点 -> 左子树 -> 右子树
list.add(root._val)
preOrder(root.left)
preOrder(root.right)
}
/* 中序遍历 */
fun inOrder(root: TreeNode?) {
if (root == null) return
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root.left)
list.add(root._val)
inOrder(root.right)
}
/* 后序遍历 */
fun postOrder(root: TreeNode?) {
if (root == null) return
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root.left)
postOrder(root.right)
list.add(root._val)
}
### 前序遍历 ###
def pre_order(root)
return if root.nil?
# 访问优先级:根节点 -> 左子树 -> 右子树
$res << root.val
pre_order(root.left)
pre_order(root.right)
end
### 中序遍历 ###
def in_order(root)
return if root.nil?
# 访问优先级:左子树 -> 根节点 -> 右子树
in_order(root.left)
$res << root.val
in_order(root.right)
end
### 后序遍历 ###
def post_order(root)
return if root.nil?
# 访问优先级:左子树 -> 右子树 -> 根节点
post_order(root.left)
post_order(root.right)
$res << root.val
end
可视化运行
Tip
深度优先搜索也可以基于迭代实现,有兴趣的读者可以自行研究。
图 7-11 展示了前序遍历二叉树的递归过程,其可分为“递”和“归”两个逆向的部分。
- “递”表示开启新方法,程序在此过程中访问下一个节点。
- “归”表示函数返回,代表当前节点已经访问完毕。
图 7-11 前序遍历的递归过程
图解 7-11:前序遍历的递归过程
沿一棵 7 节点二叉树演示前序遍历,展示访问节点与向上返回的区别。
输入为 7 节点普通二叉树:根节点为 1,1 的左右子节点是 2、3,2 的左右子节点是 4、5,3 的左右子节点是 6、7;4、5、6、7 为叶节点。
前序遍历按“根 → 左子树 → 右子树”执行:每次首次进入非空节点时立即记录其值,再依次递归处理左、右子树;遇到空节点直接返回。
调用路径指从根到当前节点、尚未结束的递归调用。下面的 11 步省略了空节点调用:7 步首次进入节点,4 步向上返回。第 4、9 步从左叶节点返回父节点,准备转向右子树;第 6、11 步则连续返回两层。
访问根节点 1
从根节点 1 开始,记录 1。调用路径为 1,输出为 [1];左子树(2、4、5)和右子树(3、6、7)均未访问,下一步进入左子节点 2。
访问左子节点 2
从 1 进入左子节点 2,记录 2。调用路径为 1 → 2,输出为 [1, 2];2 的左右叶节点 4、5 和根的右子树(3、6、7)尚未访问,下一步进入 4。
访问叶节点 4
从 2 进入左叶节点 4,记录 4。调用路径为 1 → 2 → 4,输出为 [1, 2, 4];4 的左右空子树调用直接返回,随后将回到 2。节点 5 和根的右子树(3、6、7)尚未访问。
从 4 返回 2
叶节点 4 处理完毕,返回父节点 2,调用路径回到 1 → 2。返回不再记录节点,输出保持 [1, 2, 4];2 的左子树已完成,下一步进入右子节点 5,根的右子树(3、6、7)仍未访问。
访问叶节点 5
从 2 进入右叶节点 5,记录 5。调用路径为 1 → 2 → 5,输出为 [1, 2, 4, 5];根的左子树已全部访问,但调用尚待返回。5 的左右空子树调用直接返回,根的右子树(3、6、7)仍未访问。
从 5 经 2 返回 1
5 处理完毕后返回 2;2 的左右子树均已完成,继续返回根节点 1。调用路径回到 1,输出保持 [1, 2, 4, 5];根的左子树处理完毕,下一步进入尚未访问的右子树(3、6、7),从节点 3 开始。
访问右子节点 3
从根节点 1 进入右子节点 3,记录 3。调用路径为 1 → 3,输出为 [1, 2, 4, 5, 3];3 的左右叶节点 6、7 尚未访问,下一步进入 6。
访问叶节点 6
从 3 进入左叶节点 6,记录 6。调用路径为 1 → 3 → 6,输出为 [1, 2, 4, 5, 3, 6];6 的左右空子树调用直接返回,随后将回到 3,只剩右叶节点 7 尚未访问。
从 6 返回 3
叶节点 6 处理完毕,返回父节点 3,调用路径回到 1 → 3。输出保持 [1, 2, 4, 5, 3, 6];3 的左子树已完成,下一步进入尚未访问的右叶节点 7。
访问叶节点 7
从 3 进入右叶节点 7,记录 7。调用路径为 1 → 3 → 7,输出集齐为 [1, 2, 4, 5, 3, 6, 7];7、3、1 的调用尚未结束,仍需完成向上返回。
从 7 经 3 返回 1,调用结束
7 的左右空子树调用结束后,沿 7 → 3 → 1 连续返回,最后结束根节点的调用。所有子树均已处理完毕,调用路径清空,最终输出仍为 [1, 2, 4, 5, 3, 6, 7]。
2. 复杂度分析¶
- 时间复杂度为 \(O(n)\) :所有节点被访问一次,使用 \(O(n)\) 时间。
- 空间复杂度为 \(O(n)\) :在最差情况下,即树退化为链表时,递归深度达到 \(n\) ,系统占用 \(O(n)\) 栈帧空间。