LeetCode刷题记录.Day31

二叉树的层序遍历

递归法

class Solution {
public:
    void order(TreeNode* cur, vector<vector<int>>& result, int depth)
    {
        if(cur == nullptr) return; //递归结束条件,指针为空
        if(result.size() == depth) result.push_back(vector<int>()); //当前层写入result
        result[depth].push_back(cur->val); //当前结点值写入当前层的数组中
        order(cur->left, result, depth + 1); //递归遍历左节点,每次递归层加一
        order(cur->right, result, depth + 1);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result; //二维数组result
        int depth = 0;
        order(root, result, depth);
        return result;
    }
};

递归的思路,看了一遍之后觉得很顺手,但是如果完全自己来写。不清楚能写成什么样。多看多练

 
posted @ 2022-12-04 21:59  凱風快晴  阅读(24)  评论(0)    收藏  举报