Given the root
of a binary tree, collect a tree’s nodes as if you were doing this:
- Collect all the leaf nodes.
- Remove all the leaf nodes.
- Repeat until the tree is empty.
Solution
每次需要删去叶子节点。
我们利用 /(dfs/):对于叶子节点的,我们将其深度返回 /(-1/). 这样我们递归返回的时候,/(h=/max(l+1,r+1)/), 第一个下标就是 /(0/).
如果当前深度和 /(ans.size()/) 相同时,我们就 /(push/_back/) 进一个新的 /(vector/). 接着我们分别递归出 /(l/_dep, r/_dep/). 然后:
/[h=/max(l/_dep, r/_dep)
/]
点击查看代码
/**
* 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 {
private:
vector<vector<int>> ans;
int height(TreeNode* rt, int cur_dep){
if(!rt) return -1;
if(ans.size()==cur_dep){
ans.push_back({});
}
int l_dep = height(rt->left, cur_dep+1);
int r_dep = height(rt->right, cur_dep+1);
int h = max(l_dep+1, r_dep+1);
ans[h].push_back(rt->val);
return h;
}
public:
vector<vector<int>> findLeaves(TreeNode* root) {
height(root, 0);
return ans;
}
};
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281165.html