力扣打卡第十五天 层次遍历非递归+递归

102. 二叉树的层序遍历

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

示例 1:

力扣打卡第十五天 层次遍历非递归+递归_第1张图片

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]

提示:

  • 树中节点数目在范围 [0, 2000] 内
  • -1000 <= Node.val <= 1000
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // vector> levelOrder(TreeNode* root) {
    //     vector>res;
    //     queueque;
    //     if(root==nullptr)return res;
    //     que.push(root);
    //     while(!que.empty()){
    //         int s=que.size();
    //         vector vec;
    //         for(int i=0;ival);
    //             que.pop();
    //             if(cur->left)que.push(cur->left);
    //             if(cur->right)que.push(cur->right);
    //         }
    //         res.push_back(vec);
    //     }
    //     return res;
    // }
    //这个层次遍历反而递归要难一点 我认为
    void order(TreeNode* cur,vector>& res,int depth){
        //int depth不可以写成int& depth
        //depth 的值会被修改,并且这种修改会影响所有后续的递归调用
        if(cur==nullptr)return;
        if(res.size()==depth)res.push_back(vector());
        //检查 res 中是否已经有对应深度的层。如果没有(即 result.size() == depth),则添加一个新的空向量来存储这一层的节点值。
        res[depth].push_back(cur->val);
        order(cur->left,res,depth+1);
        order(cur->right,res,depth+1);
    }

    vector> levelOrder(TreeNode* root) {
        vector>res;
        int depth=0;//层数从0开始
        order(root,res,depth);
        return res;
    }
};

你可能感兴趣的:(算法,leetcode,职场和发展)