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;
        }
    };
    
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7018590.html
Copyright © 2011-2022 走看看