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
  • 相关阅读:
    POJ 1611 The Suspects
    POJ 2001 Shortest Prefixes(字典树)
    HDU 1251 统计难题(字典树 裸题 链表做法)
    G++ C++之区别
    PAT 乙级 1013. 数素数 (20)
    PAT 乙级 1012. 数字分类 (20)
    PAT 乙级 1009. 说反话 (20)
    PAT 乙级 1008. 数组元素循环右移问题 (20)
    HDU 6063 17多校3 RXD and math(暴力打表题)
    HDU 6066 17多校3 RXD's date(超水题)
  • 原文地址:https://www.cnblogs.com/wangxf2019/p/13264393.html
Copyright © 2011-2022 走看看