当前位置: 代码迷 >> 综合 >> Leetcode865. Smallest Subtree with all the Deepest Nodes
  详细解决方案

Leetcode865. Smallest Subtree with all the Deepest Nodes

热度:69   发布时间:2023-11-22 09:11:10.0

感觉树的题都挺难的,因为要写递归吧。。感觉自己一直不会写递归。闲话少说言归正传
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.

题目挺绕的hhh,简单就是求最深的结点的父节点。

 
 

比如这棵树,就应该返回2这个结点。

思路还是递归,写一个dfs。第一个技巧,是将判断结点深度改为判断结点的高度,所以最深的叶节点就是0。

第二trick就是用 pair<int,TreeNode*> 来用来保存上一层返回的高度值和那个最深结点的父节点。

dfs的基本思路是如果结点不空,比较左孩子返回的pair和右孩子返回的pair:

  • 如果p1.first==p2.first,则说明他的左右孩子深度相同,所以返回p1或p2的first+1 和当前结点
  • 如果p1.first>p2.first,则说明左孩子的叶节点深度更深,所以返回p1的first+1和左孩子的保存的最深结点的父节点
  • 如果p1.first<p2.first,则说明右孩子的叶节点深度更深,所以返回p2的first+1和右孩子的保存的最深结点的父节点

递归终止的条件是root==NULL

AC代码:

/*** 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<int,TreeNode*>dfs(TreeNode* root){if(root==NULL){return {0,root};}pair<int,TreeNode*> p1=dfs(root->left);pair<int,TreeNode*> p2=dfs(root->right);if(p1.first==p2.first){return {p1.first+1,root};}else if(p1.first>p2.first){return {p1.first+1,p1.second};}else return {p2.first+1,p2.second};}
};

 

  相关解决方案