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 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::cell::RefCell;
use std::rc::Rc;
impl Solution {
/// ## 解题思路
/// - 递归
/// 1. 如果root为None, 则结果为None;
/// 2. 否则,root不为空, left, right分别为其左右子树根节点;
/// 3. 如果left, right均为None, 则当前节点为叶子节点, 返回该节点;
/// 4. 如果left为None, right不为None, 则最深叶节点的最近公共祖先一定在right中,
/// 递归求取以right为根的lca;
/// 5. 如果left不为None, right为None, 则递归left;
/// 6. 否则left, right都不为None, 则须判断left,right的高度
/// 6.1. 如果left_heigh == right_heigh, 则当前节点为lca;
/// 6.2. 否则递归heigh大的那一个;
pub fn lca_deepest_leaves(
root: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
// 获取树的高度
fn get_heigh(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
None => 0,
Some(root) => {
get_heigh(&root.borrow().left).max(get_heigh(&root.borrow().right)) + 1
}
}
}
match root {
None => None,
Some(root) => match (root.borrow().left.clone(), root.borrow().right.clone()) {
(None, None) => Some(root.clone()),
(Some(left), None) => Solution::lca_deepest_leaves(Some(left.clone())),
(None, Some(right)) => Solution::lca_deepest_leaves(Some(right.clone())),
(Some(left), Some(right)) => {
let left_heigh = get_heigh(&Some(left.clone()));
let right_heigh = get_heigh(&Some(right.clone()));
if left_heigh == right_heigh {
return Some(root.clone());
} else if left_heigh > right_heigh {
return Solution::lca_deepest_leaves(Some(left.clone()));
} else {
return Solution::lca_deepest_leaves(Some(right.clone()));
}
}
},
}
}
}
// @lc code=end
|