aboutsummaryrefslogtreecommitdiff
path: root/count_complete_tree_node.rs
blob: 48598629a6eab1bce0029a45dcb1c84a4e4ff1fb (plain)
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
#[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::rc::Rc;
use std::cell::RefCell;
impl Solution {
    pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if let Some(r) = root {
            let ld = {
                let mut h = 1;
                let mut node = r.borrow().left.clone();
                while let Some(n) = node {
                    h += 1;
                    node = n.borrow().left.clone();
                }
                h
            };
            let rd = {
                let mut h = 1;
                let mut node = r.borrow().right.clone();
                while let Some(n) = node {
                    h += 1;
                    node = n.borrow().right.clone();
                }
                h
            };
            if ld == rd {
                2i32.pow(ld) - 1
            } else {
                1 + Solution::count_nodes(r.borrow().left.clone()) + Solution::count_nodes(r.borrow().right.clone())
            }
        } else {
            0
        }
    }
}