|
| 1 | +package binary_tree; |
| 2 | + |
| 3 | +/** |
| 4 | + * Description: https://leetcode.com/problems/count-complete-tree-nodes |
| 5 | + * Difficulty: Medium |
| 6 | + */ |
| 7 | +public class CountCompleteTreeNodes { |
| 8 | + |
| 9 | + /** |
| 10 | + * Time complexity: O(log n * log n) |
| 11 | + * Space complexity: O(1) |
| 12 | + */ |
| 13 | + public int countNodesViaBinarySearch(TreeNode root) { |
| 14 | + if (root == null) return 0; |
| 15 | + |
| 16 | + int depth = findDepth(root); |
| 17 | + int lastLevelNodesNumber = findLastLevelNodesNumber(root, depth); |
| 18 | + |
| 19 | + return (int) Math.pow(2, depth) - 1 + lastLevelNodesNumber; |
| 20 | + } |
| 21 | + |
| 22 | + private int findLastLevelNodesNumber(TreeNode root, int depth) { |
| 23 | + // last level has from 1 to 2^depth nodes |
| 24 | + int left = 0; |
| 25 | + int right = (int) Math.pow(2, depth) - 1; |
| 26 | + |
| 27 | + while (left <= right) { |
| 28 | + int mid = left + (right - left) / 2; |
| 29 | + if (isExist(root, depth, mid)) { |
| 30 | + left = mid + 1; |
| 31 | + } else { |
| 32 | + right = mid - 1; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return left; |
| 37 | + } |
| 38 | + |
| 39 | + private boolean isExist(TreeNode root, int depth, int idx) { |
| 40 | + // use BS to reconstruct the sequence of moves from root to idx node |
| 41 | + int left = 0; |
| 42 | + int right = (int) Math.pow(2, depth) - 1; |
| 43 | + |
| 44 | + for (int i = 0; i < depth; i++) { |
| 45 | + int mid = left + (right - left) / 2; |
| 46 | + if (idx <= mid) { |
| 47 | + root = root.left; |
| 48 | + right = mid; |
| 49 | + } else { |
| 50 | + root = root.right; |
| 51 | + left = mid + 1; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return root != null; |
| 56 | + } |
| 57 | + |
| 58 | + private int findDepth(TreeNode root) { |
| 59 | + int depth = 0; |
| 60 | + while (root.left != null) { |
| 61 | + root = root.left; |
| 62 | + depth++; |
| 63 | + } |
| 64 | + |
| 65 | + return depth; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Time complexity: O(n) |
| 70 | + * Space complexity: O(h) |
| 71 | + */ |
| 72 | + public int countNodesNaiveApproach(TreeNode root) { |
| 73 | + if (root == null) return 0; |
| 74 | + return 1 + countNodesNaiveApproach(root.left) + countNodesNaiveApproach(root.right); |
| 75 | + } |
| 76 | + |
| 77 | + private static class TreeNode { |
| 78 | + int val; |
| 79 | + TreeNode left; |
| 80 | + TreeNode right; |
| 81 | + } |
| 82 | +} |
0 commit comments