|
1 | 1 | public class HelloWorld {
|
2 |
| - private static int result = Integer.MIN_VALUE; |
3 |
| - |
4 |
| - public static int maxPathSum(TreeNode root) { |
5 |
| - result = Integer.MIN_VALUE; |
| 2 | + public int countNodes(TreeNode root) { |
6 | 3 | if (root == null) {
|
7 | 4 | return 0;
|
8 | 5 | }
|
9 |
| - maxSum(root); |
10 |
| - return result; |
| 6 | + |
| 7 | + final int depth = depthTree(root) - 1; |
| 8 | + if (depth == 0) { |
| 9 | + return 1; |
| 10 | + } |
| 11 | + |
| 12 | + int left = 0, right = (int) Math.pow(2, depth) - 1, middle; |
| 13 | + while (left <= right) { |
| 14 | + middle = left + (right - left) / 2; |
| 15 | + if (exists(root, depth, middle)) left = middle + 1; |
| 16 | + else right = middle - 1; |
| 17 | + } |
| 18 | + |
| 19 | + return (int) Math.pow(2, depth) - 1 + left; |
11 | 20 | }
|
12 | 21 |
|
13 |
| - private static int maxSum(TreeNode root) { |
| 22 | + private static boolean exists(TreeNode root, int depth, int index) { |
| 23 | + TreeNode current = root; |
| 24 | + int value = -1; |
| 25 | + for (int i = 0 ; i < depth ; i++) { |
| 26 | + final int middle = (int) Math.pow(2, depth - 1 - i); |
| 27 | + if (index > value + middle) { |
| 28 | + current = current.right; |
| 29 | + value += middle; |
| 30 | + } else { |
| 31 | + current = current.left; |
| 32 | + } |
| 33 | + } |
| 34 | + return current != null; |
| 35 | + } |
| 36 | + |
| 37 | + private static int depthTree(TreeNode root) { |
14 | 38 | if (root == null) {
|
15 | 39 | return 0;
|
16 | 40 | }
|
17 | 41 |
|
18 |
| - final int maxGainLeftSubtree = Math.max(maxSum(root.left), 0); |
19 |
| - final int maxGainRightSubtree = Math.max(maxSum(root.right), 0); |
20 |
| - final int maxPathSum = root.val + maxGainLeftSubtree + maxGainRightSubtree; |
21 |
| - result = Math.max(result, maxPathSum); |
22 |
| - |
23 |
| - return Math.max(root.val + maxGainLeftSubtree, root.val + maxGainRightSubtree); |
| 42 | + return 1 + Math.max(depthTree(root.left), depthTree(root.right)); |
24 | 43 | }
|
25 | 44 | }
|
0 commit comments