zoukankan      html  css  js  c++  java
  • [LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

    方法一:

        使用队列辅助,做二叉树的层序遍历,这里由于需要将每层的节点分开,需要在节点入队列的同时,记录节点的层次,

    整是套用使用队列对二叉树做层次遍历的框架。代码如下:

    /*
     * @Descripttion: 
     * @version: 
     * @Author: wangxf
     * @Date: 2020-07-06 23:39:37
     * @LastEditors: Do not edit
     * @LastEditTime: 2020-07-07 00:22:54
     */ 
    /*
     * @lc app=leetcode.cn id=102 lang=cpp
     *
     * [102] 二叉树的层序遍历
     */
    
    // @lc code=start
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    
    struct NodeInfo
    {
        TreeNode* ptr = nullptr;
        int level = 0;
        NodeInfo(TreeNode* node_ptr,int node_level):
        ptr(node_ptr),level(node_level)
        {}
    
    };
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root)
        {
            
            std::vector<vector<int>> res;
            if(!root) return res;
            std::queue<NodeInfo> q;
            NodeInfo root_node(root,0);
            q.push(root_node);
            while(!q.empty())
            {
                NodeInfo cur_node = q.front();
                q.pop();
                int cur_level = cur_node.level;
                int cur_node_val = cur_node.ptr->val;
                if(res.size()<cur_level+1)
                {
                    vector<int> tempVec;
                    res.push_back(tempVec);
                }
                res[cur_level].push_back(cur_node_val);
                if(cur_node.ptr->left)
                {
                   NodeInfo leftNode(cur_node.ptr->left,cur_level+1);
                   q.push(leftNode);
                }
                if(cur_node.ptr->right)
                {
                   NodeInfo rightNode(cur_node.ptr->right,cur_level+1);
                   q.push(rightNode);
                }
            }
            return res;
        }
    };
    // @lc code=end
  • 相关阅读:
    Linux(Centos)安装图形化界面步骤
    Delphi 取得桌面文件夹的路径和取得我的文档的路径
    Nginx [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
    待查消息
    WM_SETFOCUS和WM_KILLFOCUS、WM_GETDLGCODE、CM_ENTER...
    WM_SIZE
    MongoDB 开启与关闭
    log4j 日志文件路径
    wamp中修改配置支持多站点
    java 下载示例
  • 原文地址:https://www.cnblogs.com/wangxf2019/p/13264393.html
Copyright © 2011-2022 走看看