102. Binary tree hierarchy traversal C++

Topic: Give you a binary tree, please return the node value obtained by traversing it in layer order.

Before the start of each layer traversal, record the number of nodes in this layer, and use the number of nodes to control the value of the inner container.

/**
 * 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<vector<int>> result;
        queue<TreeNode*>q1;//使用队列遍历二叉树
        if(root)
            q1.push(root);//根结点入队

        while(!q1.empty())
        {
    
    
        	vector<int>v1;//小容器装每一层的结果
            int len=q1.size();//在每一层遍历开始前,记录这一层的结点数量
      
            for(int i=0;i<len;++i)
            {
    
    
                TreeNode* node = q1.front();//返回队头第一个元素
                v1.push_back(node->val);//追加到小容器
                if(node->left)
                    q1.push(node->left);
                if(node->right)
                    q1.push(node->right);
                q1.pop();//移除队头元素
            }
            result.push_back(v1);//将小容器追加到大容器
        }
        return result;
    }
};

Guess you like

Origin blog.csdn.net/qq_41363459/article/details/112912133