LEETCODE解题记录——按层输出二叉树

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],

            3
           / \
          9  20
            /  \
           15   7

返回其层次遍历结果: [ [3], [9,20], [15,7] ]

题目分析:题目要求按层次遍历二叉树,并且将每层的结果存入一维数组中,最后总的结果存入二维数组中并且返回。

根据题目要求,因为每一层的结果都要输入一维数组中,我们可以考虑引入一个cur值来记录每一层节点的数目。

同时,由于要遍历完整棵树,所以可以考虑引入一个队列,将每一层的节点存入队列中,遍历到该节点后,将其孩子存入队列后,该节点出队。以此循环,即可遍历完整棵树。‘

vector<vector<int> > levelOrder(TreeNode* root) {
    vector <vector <int> > res;
    queue <TreeNode *> Queue;
    if (!root)
        return res;
    Queue.push(root); //根节点进队
    while (!Queue.empty()) {
        int cur = Queue.size();   //当前层数的节点数量
        vector <int> level;
        for (int i = 0; i < cur; ++i) {
            TreeNode *temp = Queue.front();
            Queue.pop();
            if (temp->left)         //若当前层节点有孩子,则孩子进队
                Queue.push(temp->left);
            if (temp->right)
                Queue.push(temp->right);
            level.push_back(temp->val);     //结果存入level中
        }
        res.push_back(level);
    }
    return res;
}

猜你喜欢

转载自blog.csdn.net/h4329201/article/details/80010510