1. 程式人生 > 其它 >leetcode 865. Smallest Subtree with all the Deepest Nodes(包含最深點的最小子樹)

leetcode 865. Smallest Subtree with all the Deepest Nodes(包含最深點的最小子樹)

技術標籤:leetcodeleetcode演算法

Given the root of a binary tree, the depth of each node is the shortest distance to the root.

Return the smallest subtree such that it contains all the deepest nodes in the original tree.

A node is called the deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is tree consisting of that node, plus the set of all descendants of that node.

Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/

Example 1:
在這裡插入圖片描述
Input: root = [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 coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.

找出包含最深點的最小子樹,最深點是指到root的距離最遠。

思路:
可按求樹的高度計算,但是返回高度的同時還要返回包含最深點的最小樹的root
如果左右子樹的高度相同,那麼當前root就可能是最小樹的root
如果左子樹高度>右子樹高度,那當前root就不是最小樹的root,最小樹在左子樹上,返回時root就是左子樹返回的root

因為又要返回高度,又要返回最小樹的root,可以定義一個class,包含這兩個成員,當然也可以返回一個Object陣列,取值時用down cast

    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        if(root == null) return null;
        return (TreeNode)(height(root)[1]);
    }
    
    Object[] height(TreeNode root) {
        if(root == null) {
            return new Object[]{-1, root};
        }
        
        Object[] left = height(root.left);
        Object[] right = height(root.right);
        
        int leftH = ((Integer)left[0]).intValue();
        int rightH = ((Integer)right[0]).intValue();
        
        if(leftH > rightH) {
            return new Object[]{leftH+1, left[1]};
        } else if(leftH < rightH) {
            return new Object[]{rightH+1, right[1]};
        }
        
        return new Object[]{leftH+1, root};
    }