1. 程式人生 > >Leetcode865. Smallest Subtree with all the Deepest Nodes

Leetcode865. Smallest Subtree with all the Deepest Nodes

感覺樹的題都挺難的,因為要寫遞迴吧。。感覺自己一直不會寫遞迴。閒話少說言歸正傳
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};
    }
};