题目地址:
https://leetcode.com/problems/find-leaves-of-binary-tree/
给定一棵二叉树,每次搜集其叶子的值,并把叶子删掉,再重复这样的操作直到整棵树都变空为止。
我们考虑每个节点应该要加到答案的哪一层里,容易发现,一个节点应该加在答案的哪个列表里与其到其左右子树最深的叶子有多少步有关(称为这个节点的高度)。所以我们可以在递归回溯的时候算得这个节点的深度,然后按照深度加到res的对应位置的列表上。代码如下:
class Solution {
public:
vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> res;
dfs(root, res);
return res;
}
int dfs(TreeNode* root, vector<vector<int>>& res) {
// 叶子的高度是0,所以规定走到null就返回-1
if (!root) return -1;
int he = 1 + max(dfs(root->left, res), dfs(root->right, res));
if (he >= res.size()) res.push_back({});
res[he].push_back(root->val);
return he;
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。