problem:
Given a binary tree rooted at
root
, the depth of each node is the shortest distance to the root.A node is deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is that node, plus the set of all descendants of that node.
Return the node with the largest depth such that it contains all the deepest nodes in its subtree.
Example 1:
Input: [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes colored in blue are the deepest nodes of the tree. The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree. The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2. Both the input and output have TreeNode type.
Note:
- The number of nodes in the tree will be between 1 and 500.
- The values of each node are unique.
思路:
利用“找小弟”的思想,分别从root的左右向下找,找到合适的结点,把这个合适结点的地址向上传(返回)。
那么如何找呢?
设leaf的deep为0,deep是向上递增的。
如果left.deep > right.deep ,则证明目标结点在左边
如果left.deep < right.deep ,则证明目标结点在右边
如果left.deep = right.deep ,则证明这个就是我们需要找的结点。
由于从下向上回溯的过程中,需要传输deep和合适结点的地址,所以我们需要用到pair<深度,结点指针>,把两个值一起返回
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return dfs(root).second;
}
// pair<深度,结点指针>
pair<int,TreeNode*> dfs(TreeNode* root){
if(!root)return{0,NULL};
pair<int,TreeNode*> ll=dfs(root->left),rr=dfs(root->right);
int ldeep=ll.first,rdeep=rr.first;
if(ldeep>rdeep)return {ldeep+1,ll.second};
if(ldeep<rdeep)return {rdeep+1,rr.second};
return {ldeep+1,root};
}
};