650. Find Leaves of Binary Tree
中文English
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example
Example1
Input: {1,2,3,4,5}
Output: [[4, 5, 3], [2], [1]].
Explanation:
1
/ \
2 3
/ \
4 5
Example2
Input: {1,2,3,4}
Output: [[4, 3], [2], [1]].
Explanation:
1
/ \
2 3
/
4
解法1:
这题应该是只能用DFS,不能用BFS。
根据每个节点的depth将其放入各自的vector。代码如下:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: the root of binary tree
* @return: collect and remove all leaves
*/
vector<vector<int>> findLeaves(TreeNode * root) {
if (!root) return result;
result.resize(1);
dfs(root);
return result;
}
private:
int dfs(TreeNode * root) {
if (!root) return 0;
if (!root->left && !root->right) {
result[0].push_back(root->val);
return 1;
};
int depth = max(dfs(root->left), dfs(root->right)) + 1;
if (depth > result.size()) result.resize(depth);
result[depth - 1].push_back(root->val);
return depth;
}
vector<vector<int>> result;
};
//simplified version;
class Solution {
public:
/*
* @param root: the root of binary tree
* @return: collect and remove all leaves
*/
vector<vector<int>> findLeaves(TreeNode * root) {
if (!root) return result;
dfs(root);
return result;
}
private:
int dfs(TreeNode * root) {
if (!root) return 0;
cout<<root->val<<endl;
int depth = max(dfs(root->left), dfs(root->right)) + 1;
if (depth > result.size()) result.resize(depth);
result[depth - 1].push_back(root->val);
return depth;
}
vector<vector<int>> result;
};