leetcode_102_Binary Tree Level Order Traversal

本文详细介绍了如何使用队列实现二叉树的层序遍历,包括二叉树的层序遍历概念、实现思路、代码解析及结果展示,帮助读者深入理解层序遍历的过程。

1.描述

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as  "{1,2,3,#,#,4,#,#,5}".

2.思路

一般的层序遍历直接打印出结果,用队列即可,但是此次的要求尼是按层次打印结果,所以考虑到用两个队列来交替存储,遍历上一层次的同时将下一层的结点存储到另一个队列中,并在将上面一层的遍历完成后交换两个队列的值。

3.代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
       List<List<Integer>>list=new ArrayList<List<Integer>>();//存储结果
       if(root==null)
    	   return list;
       Queue<TreeNode>q1=new LinkedList<TreeNode>();//交替存储相邻两层的结点
       Queue<TreeNode>q2=new LinkedList<TreeNode>();
       Queue<TreeNode>temp=null;
       List<Integer>subList=null;//存储一层的结点的值
       q1.add(root);
       TreeNode top=null;
       while(!q1.isEmpty())
       {
    	   subList=new ArrayList<Integer>();
    	   while(!q1.isEmpty())//循环遍历一层结点并将下一层结点存储到队列中
    	   {
    		   top=q1.peek();
    		   q1.poll();
    		   if(top.left!=null)
    			   q2.add(top.left);
    		   if(top.right!=null)
    			   q2.add(top.right);
    		   subList.add(top.val);
    	   }
    	   list.add(subList);
    	   temp=q2;//交换两个队列的值,使q1一直指向要遍历的那一层
    	   q2=q1;
    	   q1=temp;
       }
       return list;
	}
}


4.结果


你提供的这段代码是用于实现**二叉树的层序遍历(Level Order Traversal)**的 C++ 实现。它使用了**广度优先搜索(BFS)**的思想,但并没有使用标准的队列(`queue`),而是通过两个 `vector` 来模拟层级的转换,是一种**简洁高效**的实现方式。 下面我们从 **语法、逻辑、设计思想、VS 兼容性、潜在问题、完整运行示例** 等多个角度进行详细分析。 --- ## ✅ 一、代码结构分析 ```cpp class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if (root == nullptr) { return {}; } vector<vector<int>> ans; vector<TreeNode*> cur = {root}; while (cur.size()) { vector<TreeNode*> nxt; vector<int> vals; for (auto node : cur) { vals.push_back(node->val); if (node->left) nxt.push_back(node->left); if (node->right) nxt.push_back(node->right); } cur = move(nxt); ans.emplace_back(vals); } return ans; } }; ``` --- ## 🧪 二、Visual Studio 兼容性说明 这段代码在 **Visual Studio(VS)完整版中是完全合法的 C++ 代码**,只要满足以下前提条件: ### ✅ 必须满足的条件: 1. **包含头文件**: - `#include <vector>`:用于 `vector`; - `#include <iostream>`(可选):如果你在 `main()` 中打印结果。 2. **定义 `TreeNode` 类型**: - 否则会报错 `identifier not found` 3. **使用 C++11 或更高标准**: - `for (auto node : cur)` 是 C++11 的范围 for; - `move(nxt)` 是 `<utility>` 中的 `std::move`,也需要 C++11 支持。 --- ## 🧩 三、完整 VS 可运行代码 下面是一个完整的 Visual Studio 可运行示例(包含 `main()` 函数): ```cpp #include <iostream> #include <vector> #include <utility> // for std::move using namespace std; // 定义树节点结构 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if (root == nullptr) { return {}; } vector<vector<int>> ans; vector<TreeNode*> cur = {root}; while (!cur.empty()) { vector<TreeNode*> nxt; vector<int> vals; for (auto node : cur) { vals.push_back(node->val); if (node->left) nxt.push_back(node->left); if (node->right) nxt.push_back(node->right); } cur = move(nxt); ans.emplace_back(vals); } return ans; } }; // 测试主函数 int main() { // 构建测试树 // 3 // / \ // 9 20 // / \ // 15 7 TreeNode* root = new TreeNode(3); root->left = new TreeNode(9); root->right = new TreeNode(20); root->right->left = new TreeNode(15); root->right->right = new TreeNode(7); Solution sol; vector<vector<int>> result = sol.levelOrder(root); cout << "层序遍历结果:" << endl; for (const auto& level : result) { for (int val : level) { cout << val << " "; } cout << endl; } // 释放内存 delete root->right->right; delete root->right->left; delete root->right; delete root->left; delete root; return 0; } ``` --- ## 🔍 四、逐行逻辑解释 | 代码 | 说明 | |------|------| | `vector<vector<int>> ans;` | 用于存储最终结果,每层一个 `vector<int>` | | `vector<TreeNode*> cur = {root};` | 当前层的节点列表,初始为根节点 | | `while (cur.size())` | 只要当前层还有节点就继续循环 | | `vector<int> vals;` | 存储当前层所有节点的值 | | `for (auto node : cur)` | 遍历当前层每个节点 | | `vals.push_back(node->val);` | 收集当前节点值 | | `nxt.push_back(node->left);` | 收集下一层节点 | | `cur = move(nxt);` | 将下一层节点移动到当前层,避免拷贝 | | `ans.emplace_back(vals);` | 将当前层的值加入结果 | --- ## 🧠 五、设计思想与优势 ### 1. **避免使用队列,使用 vector 模拟层级遍历** - 用 `vector<TreeNode*> cur` 表示当前层; - 用 `vector<TreeNode*> nxt` 表示下一层; - 每次遍历完当前层后,将 `nxt` 移动赋值给 `cur`。 ### 2. **使用 `std::move` 提高效率** - `cur = move(nxt);` 避免了拷贝构造; - 对于大型树结构,这能显著提升性能。 ### 3. **每层单独收集值,便于组织结果** - `vals` 收集当前层的值; - `ans.emplace_back(vals)` 构造最终结果。 --- ## ⚠️ 六、潜在问题与注意事项 | 问题 | 原因 | 建议 | |------|------|------| | 缺少 `TreeNode` 定义 | 未定义节点结构 | 自定义 `TreeNode` | | 内存泄漏 | 没有 `delete` 创建的节点 | 测试后记得释放内存 | | 不使用 `std::move` | 会触发拷贝构造 | 使用 `cur = move(nxt)` 提高性能 | | 缺少头文件 | 如 `<vector>`、`<utility>` | 添加必要头文件 | --- ## ✅ 七、总结一句话: > 这段代码使用 `vector` 和 `std::move` 实现了一种简洁高效的层序遍历方式,适用于 Visual Studio 环境,只需要补充 `TreeNode` 定义和内存释放即可完整运行。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值