[LintCode] 596 Minimum Subtree 解题报告

Description
Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.

Notice
LintCode will print the subtree which root is your return node.
It's guaranteed that there is only one subtree with minimum sum and the given binary tree is not an empty tree.


Example
Given a binary tree:

      1
    /  
 -5      2
 /     /  
0   2 -4  -5
return the node 1.

5/8/2017

算法班

未经测试

 1 public class Solution {
 2     /**
 3      * @param root the root of binary tree
 4      * @return the root of the minimum subtree
 5      */
 6 
 7     class Result {
 8         int sum;
 9         TreeNode root;
10         public Result(TreeNode root, int sum) {
11             this.sum = sum;
12             this.root = root;
13         }
14     }
15 
16     private Result subtree = null;
17 
18     public TreeNode findSubtree(TreeNode root) {
19         if (root == null) return null;
20         Result _ = getMinSum(root);
21         return subtree.root;
22     }
23     private Result getMinSum(TreeNode root) {
24         if (root == null) return null;
25         if (root.left == null && root.right == null) {
26             Result ret = new Result(root, root.val);
27 
28             if (subtree == null || root.val < sum) {
29                 subtree = ret;
30             } 
31             return ret;
32         }
33         Result leftResult = getMinSum(root.left);
34         Result rightResult = getMinSum(root.right);
35 
36         Result current = new Result(root, root.val + leftResult == null? 0: leftResult.sum + rightResult == null? 0: rightResult.sum);
37 
38         if (current.sum < sum) {
39             subtree = current;
40         }
41         return current;
42     }
43 
44 }

九章解法:

(第二种解法居然不会溢出吗)

http://www.jiuzhang.com/solutions/minimum-subtree/

原文地址:https://www.cnblogs.com/panini/p/6828753.html