二叉树层次遍历后输出 c++

这个必须得记录一下,尝试了一上午,经过n次的timeout之后结果,也没有找到前人合适的code。

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
       vector<vector<int>> res(0);
        if(!root) return res;
        int row = 1;//树的第row行
        int nonull = 0;//当前队列中非空节点
        int last_nonull = 0;//当前第row行中的非空节点数量
        //construct queue
        std::deque<TreeNode*> que;
        que.push_back(root);
        nonull++;
        last_nonull = nonull;
        while(nonull > 0){
            vector<int> temp_vec;
            res.resize(row);
            int this_nonull = 0;//当前层中已经遍历过的非空节点个数
            while(this_nonull < last_nonull)
            {
                this_nonull++;
                temp_vec.push_back(que.front()->val);
                if(que.front()->left){
                    que.push_back(que.front()->left);
                    nonull++;
                }
                if(que.front()->right){
                    que.push_back(que.front()->right);
                    nonull++;
                }
                nonull--;
                que.pop_front();
            }            
            res[row-1] = temp_vec;
            row++;
            last_nonull = nonull;
        }        
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树层次遍历,也称为广度优先搜索(Breadth-First Search, BFS),是一种按照从上到下、从左到右的顺序逐层遍历树节点的方法。在C++中,我们可以使用队列数据结构来实现这一过程,因为队列的特点是先进先出(FIFO),非常适合处理二叉树层次遍历。 以下是一个简单的C++代码示例,展示了如何使用层次遍历方法遍历二叉树: ```cpp #include <iostream> #include <queue> using namespace std; // 定义二叉树结点 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 层次遍历函数 void levelOrderTraversal(TreeNode* root) { if (root == nullptr) return; queue<TreeNode*> q; // 创建一个队列 q.push(root); // 将根节点入队 while (!q.empty()) { int size = q.size(); // 当前层的节点数量 for (int i = 0; i < size; i++) { TreeNode* node = q.front(); // 弹出队首元素 cout << node->val << " "; // 访问节点值 // 将子节点入队,继续下一层 if (node->left) q.push(node->left); if (node->right) q.push(node->right); } cout << endl; // 每层结束后换行 q.pop(); // 出队已访问的节点 } } int main() { // 示例:创建一个二叉树并进行层次遍历 TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); levelOrderTraversal(root); // 输出:1 2 3 4 5 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值