-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path222.count-complete-tree-nodes.rs
67 lines (62 loc) · 1.8 KB
/
222.count-complete-tree-nodes.rs
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
61
62
63
64
65
66
67
/*
* @lc app=leetcode id=222 lang=rust
*
* [222] Count Complete Tree Nodes
*/
// @lc code=start
// Definition for a binary tree node.
// #[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 {
// Self::count_naive(root)
Self::count_height(root)
}
pub fn count_naive(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
Some(rc_node) => {
let tree_node = rc_node.borrow();
Self::count_naive(tree_node.left.clone()) +
Self::count_naive(tree_node.right.clone()) + 1
},
None => 0
}
}
pub fn height(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
Some(rc_node) => Self::height(rc_node.borrow().left.clone()) + 1,
None => -1
}
}
pub fn count_height(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
Some(rc_node) => {
let h = Self::height(Some(rc_node.clone()));
if Self::height(rc_node.borrow().right.clone()) == h - 1 {
(1 << h) + Self::count_height(rc_node.borrow().right.clone())
} else {
(1 << (h - 1)) + Self::count_height(rc_node.borrow().left.clone())
}
},
None => 0
}
}
}
// @lc code=end