Cover image for Interview Classic 150 Questions P222 Count Complete Tree Nodes

Interview Classic 150 Questions P222 Count Complete Tree Nodes


Timeline

timeline

2025-10-29

init


Problem:

Using the properties of a complete binary tree:

  • For any node in a complete binary tree, either its left subtree or right subtree must be a full binary tree.
  • To calculate the height of a complete binary tree, you only need to go left from the root node and record the height.
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
// Definition for a binary tree node.
struct Solution;

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;

impl Solution {
pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
// Calculate height
fn height(mut node: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut h = 0;
// For a complete binary tree, going left from the root node can calculate the height of the complete binary tree.
while let Some(n) = node {
h += 1;
node = n.borrow().left.clone();
}
h
}

match root {
None => 0,
Some(node) => {
// Left subtree height
let left_h = height(node.borrow().left.clone());
// Right subtree height
let right_h = height(node.borrow().right.clone());

if left_h == right_h {
// If left subtree height equals right subtree height, then the left subtree must be a full binary tree.
// A full binary tree of height h has 2^h - 1 nodes, plus the root node.
1 + (1 << left_h) - 1 + Self::count_nodes(node.borrow().right.clone())
} else { // left_h = right_h + 1
// If the height of the left subtree is greater than the height of the right subtree, it indicates that the right subtree must be a full binary tree.
1 + (1 << right_h) - 1 + Self::count_nodes(node.borrow().left.clone())
}
}
}
}
}

fn main() {
println!("Hello, world!");
}