102. 二叉树的层序遍历

题目描述:

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

 返回其层次遍历结果:

示例:
二叉树:[3,9,20,null,null,15,7],

思想:

访问过程中,只需要将同一层中的节点同时入队列即可。在将该queue中所有元素出队列的同时,将下一层的元素进队列,完成交接。

代码:

/**
 * 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;
        if(root==NULL)   //注意判断根为空的情况
            return res;
        queue<TreeNode*> Q;
        Q.push(root);
        while(!Q.empty()){
            vector<int> ans;
            int width = Q.size();    //对队列中的多个结点进行处理(队列中存在的结点为同一层的结点)
            for(int i=0;i<width;i++){
                TreeNode* p=Q.front();
                ans.push_back(p->val);
                Q.pop();
                if(p->left)
                    Q.push(p->left);
                if(p->right)
                    Q.push(p->right);
            }
            res.push_back(ans);
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/thefatcat/p/12726063.html