[Google] LeetCode 366 Find Leaves of Binary Tree 思维+DFS
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
给定一个二叉树,每次输出叶子节点,然后去除叶子节点,不断重复直到根节点也被删除。这道题的思路其实感性来看就是要剥开每一层的节点,然后存储起来。
实际上我们也不需要真正将节点去除。我们要记录每一个节点到叶子节点的距离,这里记为 \(lev\),叶子节点到本身的距离记为 \(1\),我们通过 \(DFS\) 来得到:
点击查看代码
/**
* 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:
int dfs(vector<vector<int>>& ans, TreeNode* root){
if(root==NULL)return 0;
int lev = max(dfs(ans, root->left), dfs(ans, root->right))+1;
if(lev>ans.size())ans.push_back(vector<int>());
ans[lev-1].push_back(root->val);
return lev;
}
public:
vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> ans;
dfs(ans, root);
return ans;
}
};