|
| 1 | +/** |
| 2 | + * [222] Count Complete Tree Nodes |
| 3 | + * |
| 4 | + * Given a complete binary tree, count the number of nodes. |
| 5 | + * |
| 6 | + * Note: |
| 7 | + * |
| 8 | + * <u>Definition of a complete binary tree from <a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a>:</u><br /> |
| 9 | + * In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h. |
| 10 | + * |
| 11 | + * Example: |
| 12 | + * |
| 13 | + * |
| 14 | + * Input: |
| 15 | + * 1 |
| 16 | + * / \ |
| 17 | + * 2 3 |
| 18 | + * / \ / |
| 19 | + * 4 5 6 |
| 20 | + * |
| 21 | + * Output: 6 |
| 22 | + * |
| 23 | + */ |
| 24 | +pub struct Solution {} |
| 25 | +use super::util::tree::{to_tree, TreeNode}; |
| 26 | + |
| 27 | +// submission codes start here |
| 28 | + |
| 29 | +use std::rc::Rc; |
| 30 | +use std::cell::RefCell; |
| 31 | +impl Solution { |
| 32 | + pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { |
| 33 | + // 0. get the hight of full nodes |
| 34 | + let mut height = 0; |
| 35 | + let mut curr = root.clone(); |
| 36 | + let mut result = 0; |
| 37 | + while let Some(inner) = curr { |
| 38 | + height += 1; |
| 39 | + result += 2_i32.pow(height-1); |
| 40 | + curr = inner.borrow().right.clone(); |
| 41 | + } |
| 42 | + if height == 0 { return result } |
| 43 | + // 1. 'binary search' to find the node number of the lowest level |
| 44 | + // the lowest level may have 0~2^H-1 node |
| 45 | + let mut curr_root = root.clone(); |
| 46 | + while height > 1 { |
| 47 | + // see if left tree is full |
| 48 | + let mut node = curr_root.clone().unwrap().borrow().left.clone(); |
| 49 | + let mut level = 2; |
| 50 | + while level < height { |
| 51 | + node = node.unwrap().borrow().right.clone(); |
| 52 | + level += 1; |
| 53 | + } |
| 54 | + if node.unwrap().borrow().right.is_some() { |
| 55 | + curr_root = curr_root.unwrap().borrow().right.clone(); |
| 56 | + result += 2_i32.pow(height-1); |
| 57 | + } else { |
| 58 | + curr_root = curr_root.unwrap().borrow().left.clone(); |
| 59 | + } |
| 60 | + height -= 1; |
| 61 | + } |
| 62 | + if curr_root.as_ref().unwrap().borrow().left.is_some() { |
| 63 | + result += 1; |
| 64 | + } |
| 65 | + result |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// submission codes end |
| 70 | + |
| 71 | +#[cfg(test)] |
| 72 | +mod tests { |
| 73 | + use super::*; |
| 74 | + |
| 75 | + #[test] |
| 76 | + fn test_222() { |
| 77 | + assert_eq!(Solution::count_nodes(tree![1,1,1,1,1,1,1]), 7); |
| 78 | + assert_eq!(Solution::count_nodes(tree![]), 0); |
| 79 | + assert_eq!(Solution::count_nodes(tree![1,1]), 2); |
| 80 | + assert_eq!(Solution::count_nodes(tree![1]), 1); |
| 81 | + assert_eq!(Solution::count_nodes(tree![1,1,1]), 3); |
| 82 | + } |
| 83 | +} |
0 commit comments