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;
        }
    };
    
  • 相关阅读:
    scala之伴生对象的继承
    scala之伴生对象说明
    “Failed to install the following Android SDK packages as some licences have not been accepted” 错误
    PATH 环境变量重复问题解决
    Ubuntu 18.04 配置java环境
    JDBC的基本使用2
    DCL的基本语法(授权)
    ZJNU 1374
    ZJNU 2184
    ZJNU 1334
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7018590.html
Copyright © 2011-2022 走看看