时间轴

2025-10-29

init


题目:

利用完全二叉树的性质:

  • 完全二叉树的某一个结点的左子树或右子树必有一颗是满二叉树
  • 完全二叉树的高度计算只需要从根节点一路向左记录高度即可
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
// 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 {
fn height(mut node: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut h = 0;
// 对于一颗完全二叉树,从根节点一直向左走可以算出完全二叉树的高度
while let Some(n) = node {
h += 1;
node = n.borrow().left.clone();
}
h
}

match root {
None => 0,
Some(node) => {
// 左子树高度
let left_h = height(node.borrow().left.clone());
// 右子树高度
let right_h = height(node.borrow().right.clone());

if left_h == right_h {
// 左子树是满的, 高度为h的满二叉树有2^h - 1个结点, 加上根节点
1 + (1 << left_h) - 1 + Self::count_nodes(node.borrow().right.clone())
} else { // left_h = right_h + 1
// 右子树是满的
1 + (1 << right_h) - 1 + Self::count_nodes(node.borrow().left.clone())
}
}
}
}
}

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