【LeetCode】102.二叉树的层次遍历 (C++)

版权声明:原创不易,且看且珍惜 https://blog.csdn.net/z13653662052/article/details/89021108

题目地址:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

题目描述:

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

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

使用队列进行层次遍历:

因为本题不光要层次遍历,且最后的结果需要分层保存(即每层结点保存在一个vector里),所以需要一个depth记录目前是第几层,一个cout记录该层有几个节点,然后利用队列先进先出,逐个遍历所有节点。

/**
 * 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==nullptr)return vector<vector<int>>{};
        queue<TreeNode*> data;
        vector<vector<int>> res;
        data.push(root);
        int depth=0;
        while(!data.empty()){
            res.push_back(vector<int> {});//开辟第几层的存储空间
            int cout = data.size();//第几层有cout个节点
            while(cout--){//遍历第几层
                res[depth].push_back(root->val);
                if(root->left != nullptr)data.push(root->left);
                if(root->right != nullptr)data.push(root->right);
                data.pop();
                if(!data.empty())root = data.front();
            }
            depth += 1;//层数加1
        }
        return res;
    }
};

递归前序遍历:(参考leetcode评论)

  • 利用depth变量记录当前在第几层(从0开始),进入下层时depth + 1
  • 如果depth >= vector.size()说明这一层还没来过,这是第一次来,所以得扩容咯;
  • 因为是前序遍历,中-左-右,对于每一层来说,左边的肯定比右边先被遍历到,实际上后序中序都是一样的
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        pre(root, 0, ans);
        return ans;
    }
    
    void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
        if (!root) return ;//void
        if (depth >= ans.size())
            ans.push_back(vector<int> {});
        ans[depth].push_back(root->val);
        pre(root->left, depth + 1, ans);
        pre(root->right, depth + 1, ans);
    }
};

猜你喜欢

转载自blog.csdn.net/z13653662052/article/details/89021108