Star

LintCode 596. Minimum Subtree

Question

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
2
3
4
5
1
/ \
-5 2
/ \ / \
0 2 -4 -5

return the node 1.

Explanation

可以用遍历的方式来递归,也可以用分治法。分治法的话要注意自己构造一个类。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// version 1 : traverse + divide conquer
public class Solution {
private TreeNode subtree = null;
private int subtreeSum = Integer.MAX_VALUE;
/**
* @param root the root of binary tree
* @return the root of the minimum subtree
*/
public TreeNode findSubtree(TreeNode root) {
helper(root);
return subtree;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int sum = helper(root.left) + helper(root.right) + root.val;
if (sum < subtreeSum) {
subtreeSum = sum;
subtree = root;
}
return sum;
}
}
// version 2: Pure divide conquer
class ResultType {
public TreeNode minSubtree;
public int sum, minSum;
public ResultType(TreeNode minSubtree, int minSum, int sum) {
this.minSubtree = minSubtree;
this.minSum = minSum;
this.sum = sum;
}
}
public class Solution {
/**
* @param root the root of binary tree
* @return the root of the minimum subtree
*/
public TreeNode findSubtree(TreeNode root) {
ResultType result = helper(root);
return result.minSubtree;
}
public ResultType helper(TreeNode node) {
if (node == null) {
return new ResultType(null, Integer.MAX_VALUE, 0);
}
ResultType leftResult = helper(node.left);
ResultType rightResult = helper(node.right);
ResultType result = new ResultType(
node,
leftResult.sum + rightResult.sum + node.val,
leftResult.sum + rightResult.sum + node.val
);
if (leftResult.minSum < result.minSum) {
result.minSum = leftResult.minSum;
result.minSubtree = leftResult.minSubtree;
}
if (rightResult.minSum < result.minSum) {
result.minSum = rightResult.minSum;
result.minSubtree = rightResult.minSubtree;
}
return result;
}
}