Leetcode 102. Binary Tree hierarchy traversal problem-solving ideas and implemented in C ++

Problem-solving ideas:

Using queues to the storage node of each layer, since the output vector, each layer is an array, so that in the circulation, need another queue, a total of two queues.

Layer is not obtained, the node updates the first queue a, b queue assigned directly to a.

 

/**
 * 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) return {};
        
        vector<vector<int> > res;
        res.push_back({root->val});
        queue<TreeNode*> a;
        if(root->left) a.push(root->left);
        if(root->right) a.push(root->right);
        while(!a.empty()){
            vector<int> num;
            queue<TreeNode*> b;
            while(!a.empty()){
                TreeNode* tmp = a.front();
                num.push_back(tmp->val);
                a.pop();
                if(tmp->left) b.push(tmp->left);
                if(tmp->right) b.push(tmp->right);
            }
            res.push_back(num);
            a = b;
        }
        return res;
    }
};

 

Online Another solution is to use only one queue, binary tree with NULL to separate each layer, did not encounter a NULL, on behalf of this layer node has access to complete.

 

 

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/92142549