implSolution { pubfncount_nodes(root: Option<Rc<RefCell<TreeNode>>>) ->i32 { // Calculate height fnheight(mut node: Option<Rc<RefCell<TreeNode>>>) ->i32 { letmut h = 0; // For a complete binary tree, going left from the root node can calculate the height of the complete binary tree. whileletSome(n) = node { h += 1; node = n.borrow().left.clone(); } h }
match root { None => 0, Some(node) => { // Left subtree height letleft_h = height(node.borrow().left.clone()); // Right subtree height letright_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()) } } } } }