zoukankan      html  css  js  c++  java
  • 102.Binary Tree Level Order Traversal

    思路:
    • 递归,利用level表示第几层。
    /**
     * 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;
            bfs(root,1,res);
            return res;
        }
        void bfs(TreeNode* root,int level,vector<vector<int>>& res){
            if(root == NULL) return ;
            vector<int> tmp;
            if(level > res.size()) res.push_back(tmp);
            res[level-1].push_back(root->val);      //注意,这里level不能替换成res.size()-1,调试了好久。。。
            bfs(root->left,level+1,res);
            bfs(root->right,level+1,res);
            
        }
    };
    
    • 迭代,利用队列,一层一层进行遍历。
    /**
     * 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) {
            if(root == NULL) return {};
            vector<vector<int>> res;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty()){
                int size = q.size();
                vector<int> level;
                for(int i = 0; i < size; i++){
                    TreeNode *tmp = q.front();
                    level.push_back(tmp->val);
                    q.pop();
                    if(tmp->left) q.push(tmp->left);
                    if(tmp->right) q.push(tmp->right);
                }
                res.push_back(level);
            }
            return res;
        }
    };
    
  • 相关阅读:
    B1028人口普查
    B1004成绩排名
    B1041考试座位号
    A1009 Product of Polynomials多项式相乘
    A1002 A+B for Polynomials 多项式相加
    B1010一元多项式求导
    A1065 A+Band C(64 bit)
    A1046 Shortest Distance 最短路径
    排序
    windows 平台使用wireshark命令行抓包
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7018590.html
Copyright © 2011-2022 走看看