【题解】二叉树的层次遍历

求二叉树的层序遍历

题目链接:求二叉树的层序遍历

解题思路1:递归

代码如下:

    void level(TreeNode* root, vector<vector<int>>& res, int depth){
        if(root == nullptr){
            return;
        }
        if(depth >= res.size()){
            res.push_back(vector<int> {});
        }
        res[depth].push_back(root->val);
        level(root->left, res, depth+1);
        level(root->right, res, depth+1);
    }
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        level(root, res, 0);
        return res;
    }

解题思路2:迭代,借助队列

代码如下:

    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr) return res;
        queue<TreeNode*> q;
        q.push(root);
        TreeNode* cur;
        while(!q.empty()){
            vector<int> row;
            int n = q.size();
            for(int i=0; i<n; ++i){
                cur = q.front();
                q.pop();
                row.push_back(cur->val);
                if(cur->left != nullptr) q.push(cur->left);
                if(cur->right != nullptr) q.push(cur->right);
            }
            res.push_back(row);
        }
        return res;
    }

你可能感兴趣的:(题目练习,数据结构)