7.2   二叉树遍历

您所在的位置:网站首页 二叉树算法复杂度 7.2   二叉树遍历

7.2   二叉树遍历

2024-07-13 12:25:04| 来源: 网络整理| 查看: 265

7.2   二叉树遍历¶

从物理结构的角度来看,树是一种基于链表的数据结构,因此其遍历方式是通过指针逐个访问节点。然而,树是一种非线性数据结构,这使得遍历树比遍历链表更加复杂,需要借助搜索算法来实现。

二叉树常见的遍历方式包括层序遍历、前序遍历、中序遍历和后序遍历等。

7.2.1   层序遍历¶

如图 7-9 所示,层序遍历(level-order traversal)从顶部到底部逐层遍历二叉树,并在每一层按照从左到右的顺序访问节点。

层序遍历本质上属于广度优先遍历(breadth-first traversal),也称广度优先搜索(breadth-first search, BFS),它体现了一种“一圈一圈向外扩展”的逐层遍历方式。

图 7-9   二叉树的层序遍历

1.   代码实现¶

广度优先遍历通常借助“队列”来实现。队列遵循“先进先出”的规则,而广度优先遍历则遵循“逐层推进”的规则,两者背后的思想是一致的。实现代码如下:

binary_tree_bfs.pydef 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 binary_tree_bfs.cpp/* 层序遍历 */ vector levelOrder(TreeNode *root) { // 初始化队列,加入根节点 queue queue; queue.push(root); // 初始化一个列表,用于保存遍历序列 vector 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; } binary_tree_bfs.java/* 层序遍历 */ List levelOrder(TreeNode root) { // 初始化队列,加入根节点 Queue queue = new LinkedList(); queue.add(root); // 初始化一个列表,用于保存遍历序列 List 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; } binary_tree_bfs.cs/* 层序遍历 */ List LevelOrder(TreeNode root) { // 初始化队列,加入根节点 Queue queue = new(); queue.Enqueue(root); // 初始化一个列表,用于保存遍历序列 List 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; } binary_tree_bfs.go/* 层序遍历 */ 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 } binary_tree_bfs.swift/* 层序遍历 */ 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 } binary_tree_bfs.js/* 层序遍历 */ 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; } binary_tree_bfs.ts/* 层序遍历 */ 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; } binary_tree_bfs.dart/* 层序遍历 */ List levelOrder(TreeNode? root) { // 初始化队列,加入根节点 Queue queue = Queue(); queue.add(root); // 初始化一个列表,用于保存遍历序列 List 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; } binary_tree_bfs.rs/* 层序遍历 */ fn level_order(root: &Rc) -> Vec { // 初始化队列,加入根节点 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 } binary_tree_bfs.c/* 层序遍历 */ 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 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; } binary_tree_bfs.kt/* 层序遍历 */ fun levelOrder(root: TreeNode?): MutableList { // 初始化队列,加入根节点 val queue = LinkedList() queue.add(root) // 初始化一个列表,用于保存遍历序列 val list = mutableListOf() 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 } binary_tree_bfs.rb### 层序遍历 ### def level_order(root) # 初始化队列,加入根节点 queue = [root] # 初始化一个列表,用于保存遍历序列 res = [] while !queue.empty? node = queue.shift # 队列出队 res 右子树 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) binary_tree_dfs.cpp/* 前序遍历 */ 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); } binary_tree_dfs.java/* 前序遍历 */ 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); } binary_tree_dfs.cs/* 前序遍历 */ 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); } binary_tree_dfs.go/* 前序遍历 */ 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) } binary_tree_dfs.swift/* 前序遍历 */ 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) } binary_tree_dfs.js/* 前序遍历 */ 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); } binary_tree_dfs.ts/* 前序遍历 */ 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); } binary_tree_dfs.dart/* 前序遍历 */ 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); } binary_tree_dfs.rs/* 前序遍历 */ fn pre_order(root: Option) -> Vec { let mut result = vec![]; if let Some(node) = root { // 访问优先级:根节点 -> 左子树 -> 右子树 result.push(node.borrow().val); result.extend(pre_order(node.borrow().left.as_ref())); result.extend(pre_order(node.borrow().right.as_ref())); } result } /* 中序遍历 */ fn in_order(root: Option) -> Vec { let mut result = vec![]; if let Some(node) = root { // 访问优先级:左子树 -> 根节点 -> 右子树 result.extend(in_order(node.borrow().left.as_ref())); result.push(node.borrow().val); result.extend(in_order(node.borrow().right.as_ref())); } result } /* 后序遍历 */ fn post_order(root: Option) -> Vec { let mut result = vec![]; if let Some(node) = root { // 访问优先级:左子树 -> 右子树 -> 根节点 result.extend(post_order(node.borrow().left.as_ref())); result.extend(post_order(node.borrow().right.as_ref())); result.push(node.borrow().val); } result } binary_tree_dfs.c/* 前序遍历 */ 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; } binary_tree_dfs.kt/* 前序遍历 */ 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) } binary_tree_dfs.rb### 前序遍历 ### def pre_order(root) return if root.nil? # 访问优先级:根节点 -> 左子树 -> 右子树 $res 右子树 in_order(root.left) $res 根节点 post_order(root.left) post_order(root.right) $res 右子树 try list.append(root.?.val); try preOrder(T, root.?.left); try preOrder(T, root.?.right); } // 中序遍历 fn inOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void { if (root == null) return; // 访问优先级:左子树 -> 根节点 -> 右子树 try inOrder(T, root.?.left); try list.append(root.?.val); try inOrder(T, root.?.right); } // 后序遍历 fn postOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void { if (root == null) return; // 访问优先级:左子树 -> 右子树 -> 根节点 try postOrder(T, root.?.left); try postOrder(T, root.?.right); try list.append(root.?.val); } 可视化运行

全屏观看 >

Tip

深度优先搜索也可以基于迭代实现,有兴趣的读者可以自行研究。

图 7-11 展示了前序遍历二叉树的递归过程,其可分为“递”和“归”两个逆向的部分。

“递”表示开启新方法,程序在此过程中访问下一个节点。 “归”表示函数返回,代表当前节点已经访问完毕。

图 7-11   前序遍历的递归过程

2.   复杂度分析¶ 时间复杂度为 \(O(n)\) :所有节点被访问一次,使用 \(O(n)\) 时间。 空间复杂度为 \(O(n)\) :在最差情况下,即树退化为链表时,递归深度达到 \(n\) ,系统占用 \(O(n)\) 栈帧空间。 欢迎在评论区留下你的见解、问题或建议


【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭