2022-05-22:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。

如何时间复杂度O(N),额外空间复杂度O(1),解决最低公共祖先问题?

力扣236。二叉树的最近公共祖先。

答案2022-05-23:

莫里斯遍历。主要是修改rust代码。

rust代码修改如下:

use std::cell::RefCell;
use std::rc::Rc; fn main() {
let mut head = Some(Rc::new(RefCell::new(TreeNode::new(1))));
let mut left_left = Some(Rc::new(RefCell::new(TreeNode::new(4))));
let mut left_right = Some(Rc::new(RefCell::new(TreeNode::new(5))));
head.as_ref().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
head.as_ref().unwrap().borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(3))));
head.as_ref()
.unwrap()
.borrow()
.left
.as_ref()
.unwrap()
.borrow_mut()
.left = Some(Rc::clone(&left_left.as_ref().unwrap()));
head.as_ref()
.unwrap()
.borrow()
.left
.as_ref()
.unwrap()
.borrow_mut()
.right = Some(Rc::clone(&left_right.as_ref().unwrap()));
let ans = Solution::lowest_common_ancestor(
Some(Rc::clone(&head.as_ref().unwrap())),
Some(Rc::clone(&left_left.as_ref().unwrap())),
Some(Rc::clone(&left_right.as_ref().unwrap())),
);
if ans.is_none() {
println!("ans = 空");
} else {
println!("ans val = {}", ans.as_ref().unwrap().borrow().val);
}
println!("-----------------");
println!("head = {}", head.as_ref().unwrap().borrow().val);
println!(
"head.left = {}",
head.as_ref()
.unwrap()
.borrow()
.left
.as_ref()
.unwrap()
.borrow()
.val
);
println!(
"head.right = {}",
head.as_ref()
.unwrap()
.borrow()
.right
.as_ref()
.unwrap()
.borrow()
.val
);
println!(
"head.left.left = {}",
head.as_ref()
.unwrap()
.borrow()
.left
.as_ref()
.unwrap()
.borrow()
.left
.as_ref()
.unwrap()
.borrow()
.val
);
println!(
"head.left.right = {}",
head.as_ref()
.unwrap()
.borrow()
.left
.as_ref()
.unwrap()
.borrow()
.right
.as_ref()
.unwrap()
.borrow()
.val
);
} pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
} impl TreeNode {
pub fn new(val: i32) -> Self {
Self {
val,
left: None,
right: None,
}
}
} pub struct Solution {} // 力扣里提交以下的代码
impl Solution {
// 该方法亮点在于:时间复杂度O(N),额外空间复杂度O(1)
pub fn lowest_common_ancestor(
mut head: Option<Rc<RefCell<TreeNode>>>,
mut o1: Option<Rc<RefCell<TreeNode>>>,
mut o2: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
// if (findFirst(o1.left, o1, o2) != null || findFirst(o1.right, o1, o2) != null) {
// return o1;
// }
if !find_first(
if o1.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&o1.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
)
.is_none()
|| !find_first(
if o1.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&o1.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
)
.is_none()
{
return if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
};
} // if (findFirst(o2.left, o1, o2) != null || findFirst(o2.right, o1, o2) != null) {
// return o2;
// }
if !find_first(
if o2.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&o2.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
)
.is_none()
|| !find_first(
if o2.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&o2.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
)
.is_none()
{
return if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
};
} //left_aim := findFirst(head, o1, o2)
let mut left_aim = find_first(
if head.is_none() {
None
} else {
Some(Rc::clone(&head.as_ref().unwrap()))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
);
// TreeNode cur = head;
let mut cur = if head.is_none() {
None
} else {
Some(Rc::clone(&head.as_ref().unwrap()))
};
// TreeNode most_right = null;
let mut most_right: Option<Rc<RefCell<TreeNode>>> = None;
// TreeNode ans = null;
let mut ans: Option<Rc<RefCell<TreeNode>>> = None;
//for cur != nil {
while !cur.is_none() {
// most_right = cur.left;
most_right = if cur.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
}; //if most_right != nil {
if !most_right.is_none() {
//while most_right.right != null && most_right.right != cur {
while !most_right.as_ref().unwrap().borrow().right.is_none()
&& !is_eq(
&Some(Rc::clone(
&most_right
.as_ref()
.unwrap()
.borrow()
.right
.as_ref()
.unwrap(),
)),
&cur,
)
{
// most_right = most_right.right;
most_right = if most_right.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&most_right
.as_ref()
.unwrap()
.borrow()
.right
.as_ref()
.unwrap(),
))
};
} //if (most_right.right == null) {
if most_right.as_ref().unwrap().borrow().right.is_none() {
// most_right.right = cur;
most_right.as_ref().unwrap().borrow_mut().right = if cur.is_none() {
None
} else {
Some(Rc::clone(&cur.as_ref().unwrap()))
};
// cur = cur.left;
cur = if cur.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
};
continue;
} else {
//most_right.right = null;
most_right.as_ref().unwrap().borrow_mut().right = None;
//if (findLeftAim(cur.left, left_aim)) {
if find_left_aim(
if cur.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
},
if left_aim.is_none() {
None
} else {
Some(Rc::clone(&left_aim.as_ref().unwrap()))
},
) {
//if (ans == null && findFirst(left_aim.right, o1, o2) != null) {
if ans.is_none()
&& !find_first(
if left_aim.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&left_aim
.as_ref()
.unwrap()
.borrow()
.right
.as_ref()
.unwrap(),
))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
)
.is_none()
{
//ans = left_aim;
ans = if left_aim.is_none() {
None
} else {
Some(Rc::clone(&left_aim.as_ref().unwrap()))
};
} // left_aim = cur;
left_aim = if cur.is_none() {
None
} else {
Some(Rc::clone(&cur.as_ref().unwrap()))
};
}
}
}
// cur = cur.right;
cur = if cur.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
};
} if !ans.is_none() {
return ans;
} else {
if !find_first(
if left_aim.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&left_aim.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
},
if o1.is_none() {
None
} else {
Some(Rc::clone(&o1.as_ref().unwrap()))
},
if o2.is_none() {
None
} else {
Some(Rc::clone(&o2.as_ref().unwrap()))
},
)
.is_none()
{
return Some(Rc::clone(&left_aim.as_ref().unwrap()));
} else {
return Some(Rc::clone(&head.as_ref().unwrap()));
}
}
}
} fn find_left_aim(
mut head: Option<Rc<RefCell<TreeNode>>>,
mut left_aim: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
let mut tail = reverse_edge(Some(Rc::clone(&head.as_ref().unwrap())));
//TreeNode cur = tail;
let mut cur = if tail.is_none() {
None
} else {
Some(Rc::clone(&tail.as_ref().unwrap()))
};
// boolean ans = false;
let mut ans = false;
while !cur.is_none() {
if is_eq(&cur, &left_aim) {
ans = true;
}
// cur = cur.right;
cur = if cur.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
};
}
reverse_edge(Some(Rc::clone(&tail.as_ref().unwrap())));
return ans;
} fn reverse_edge(mut from: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
//TreeNode pre = null;
let mut pre: Option<Rc<RefCell<TreeNode>>> = None;
//TreeNode next = null;
let mut next: Option<Rc<RefCell<TreeNode>>> = None;
while !is_eq(&from, &None) {
// next = from.right;
next = if from.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&from.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
};
// from.right = pre;
from.as_ref().unwrap().borrow_mut().right = if pre.is_none() {
None
} else {
Some(Rc::clone(&pre.as_ref().unwrap()))
};
// pre = from;
pre = if from.is_none() {
None
} else {
Some(Rc::clone(&from.as_ref().unwrap()))
};
// from = next;
from = if next.is_none() {
None
} else {
Some(Rc::clone(&next.as_ref().unwrap()))
};
}
return pre;
} fn find_first(
mut head: Option<Rc<RefCell<TreeNode>>>,
mut o1: Option<Rc<RefCell<TreeNode>>>,
mut o2: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
//if head == nil {
if head.is_none() {
return None;
}
//cur := head
let mut cur: Option<Rc<RefCell<TreeNode>>> = Some(Rc::clone(&head.as_ref().unwrap()));
//var most_right *TreeNode
let mut most_right: Option<Rc<RefCell<TreeNode>>> = None;
//var first *TreeNode
let mut first: Option<Rc<RefCell<TreeNode>>> = None;
//for cur != nil {
while !cur.is_none() {
//most_right = cur.left;
most_right = if cur.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
}; //if most_right != nil {
if !most_right.is_none() {
while !most_right.as_ref().unwrap().borrow().right.is_none()
&& !is_eq(&most_right.as_ref().unwrap().borrow().right, &cur)
{
//most_right = most_right.right;
most_right = if most_right.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&most_right
.as_ref()
.unwrap()
.borrow()
.right
.as_ref()
.unwrap(),
))
};
}
if is_eq(&most_right.as_ref().unwrap().borrow().right, &None) {
if is_eq(&first, &None) && (is_eq(&cur, &o1) || is_eq(&cur, &o2)) {
// first = cur;
first = if cur.is_none() {
None
} else {
Some(Rc::clone(&cur.as_ref().unwrap()))
};
}
// most_right.right = cur;
most_right.as_ref().unwrap().borrow_mut().right = if cur.is_none() {
None
} else {
Some(Rc::clone(&cur.as_ref().unwrap()))
};
// cur = cur.left;
cur = if cur.as_ref().unwrap().borrow().left.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().left.as_ref().unwrap(),
))
};
continue;
} else {
//most_right.right = nil;
most_right.as_ref().unwrap().borrow_mut().right = None;
}
} else {
//if first == nil && (cur == o1 || cur == o2) {
if is_eq(&first, &None) && (is_eq(&cur, &o1) || is_eq(&cur, &o2)) {
// first = cur;
first = if cur.as_ref().is_none() {
None
} else {
Some(Rc::clone(&cur.as_ref().unwrap()))
};
}
}
// cur = cur.right;
cur = if cur.as_ref().unwrap().borrow().right.is_none() {
None
} else {
Some(Rc::clone(
&cur.as_ref().unwrap().borrow().right.as_ref().unwrap(),
))
};
}
return first;
} fn is_eq(o1: &Option<Rc<RefCell<TreeNode>>>, o2: &Option<Rc<RefCell<TreeNode>>>) -> bool {
if o1.is_none() && o2.is_none() {
return true;
}
if o1.is_none() || o2.is_none() {
return false;
}
return o1.as_ref().unwrap().borrow().val == o2.as_ref().unwrap().borrow().val;
}

执行结果如下:


答案2022-05-22:

莫里斯遍历。

答案用rust编写,答案有误。代码如下:

use std::cell::RefCell;
use std::rc::Rc; fn main() {
let mut head = Rc::new(RefCell::new(Some(TreeNode::new(3))));
let mut left = Rc::clone(&head.borrow().as_ref().unwrap().left);
*left.borrow_mut() = Some(TreeNode::new(5)); let mut right = Rc::clone(&head.borrow().as_ref().unwrap().right);
*right.borrow_mut() = Some(TreeNode::new(1)); let mut head2 = Rc::clone(&head.borrow().as_ref().unwrap().left);
let mut leftleft = Rc::clone(&head2.borrow().as_ref().unwrap().left);
*leftleft.borrow_mut() = Some(TreeNode::new(6)); let mut rightright = Rc::clone(&head2.borrow().as_ref().unwrap().right);
*rightright.borrow_mut() = Some(TreeNode::new(2)); let ans = lowest_common_ancestor(
Rc::clone(&head),
Rc::clone(&leftleft),
Rc::clone(&rightright),
);
if ans.borrow().is_none() {
println!("None");
} else {
println!("ans = {}", ans.borrow().as_ref().unwrap().val);
} let mut left = Rc::clone(&head.borrow().as_ref().unwrap().left);
let mut right = Rc::clone(&head.borrow().as_ref().unwrap().right);
println!("head = {}", head.borrow().as_ref().unwrap().val);
println!("p = {}", left.borrow().as_ref().unwrap().val);
println!("q = {}", right.borrow().as_ref().unwrap().val); println!("---------------");
println!("head = {}", head.borrow().as_ref().unwrap().val);
println!("left = {}", left.borrow().as_ref().unwrap().val);
println!("right = {}", right.borrow().as_ref().unwrap().val);
println!("left.left = {}", leftleft.borrow().as_ref().unwrap().val);
println!("left.right = {}", rightright.borrow().as_ref().unwrap().val);
} pub struct TreeNode {
pub val: i32,
pub left: Rc<RefCell<Option<TreeNode>>>,
pub right: Rc<RefCell<Option<TreeNode>>>,
} impl TreeNode {
pub fn new(val: i32) -> Self {
Self {
val,
left: Rc::new(RefCell::new(None)),
right: Rc::new(RefCell::new(None)),
}
}
} fn lowest_common_ancestor(
mut head: Rc<RefCell<Option<TreeNode>>>,
mut o1: Rc<RefCell<Option<TreeNode>>>,
mut o2: Rc<RefCell<Option<TreeNode>>>,
) -> Rc<RefCell<Option<TreeNode>>> {
if !find_first(
Rc::clone(&o1.borrow().as_ref().unwrap().left),
Rc::clone(&o1),
Rc::clone(&o2),
)
.borrow()
.is_none()
|| !find_first(
Rc::clone(&o1.borrow().as_ref().unwrap().right),
Rc::clone(&o1),
Rc::clone(&o2),
)
.borrow()
.is_none()
{
return Rc::clone(&o1);
} if !find_first(
Rc::clone(&o2.borrow().as_ref().unwrap().left),
Rc::clone(&o1),
Rc::clone(&o2),
)
.borrow()
.is_none()
|| !find_first(
Rc::clone(&o2.borrow().as_ref().unwrap().right),
Rc::clone(&o1),
Rc::clone(&o2),
)
.borrow()
.is_none()
{
return Rc::clone(&o1);
}
let mut left_aim: Rc<RefCell<Option<TreeNode>>> =
find_first(Rc::clone(&head), Rc::clone(&o1), Rc::clone(&o2));
let mut cur: Rc<RefCell<Option<TreeNode>>> = Rc::clone(&head);
let mut most_right: Rc<RefCell<Option<TreeNode>>> = Rc::new(RefCell::new(None));
let mut ans: Rc<RefCell<Option<TreeNode>>> = Rc::new(RefCell::new(None));
while cur.borrow().is_none() {
most_right = Rc::clone(&cur.borrow().as_ref().unwrap().left);
if !most_right.borrow().is_none() {
while !Rc::clone(&most_right.borrow().as_ref().unwrap().right)
.borrow()
.is_none()
&& is_eq(
Rc::clone(&most_right.borrow().as_ref().unwrap().right),
Rc::clone(&cur),
)
{
let mut mostrightright = Rc::clone(&most_right.borrow().as_ref().unwrap().right);
most_right = Rc::clone(&mostrightright);
}
if Rc::clone(&most_right.borrow().as_ref().unwrap().right)
.borrow()
.is_none()
{
let mut mostrightright = Rc::clone(&most_right.borrow().as_ref().unwrap().right);
mostrightright = Rc::clone(&cur);
let mut curleft = Rc::clone(&cur.borrow().as_ref().unwrap().left);
cur = Rc::clone(&curleft);
continue;
} else {
let mut mostrightright = Rc::clone(&most_right.borrow().as_ref().unwrap().right);
mostrightright = Rc::new(RefCell::new(None));
if find_left_aim(
Rc::clone(&cur.borrow().as_ref().unwrap().left),
Rc::clone(&left_aim),
) {
if ans.borrow().is_none()
&& !find_first(
Rc::clone(&left_aim.borrow().as_ref().unwrap().right),
Rc::clone(&o1),
Rc::clone(&o2),
)
.borrow()
.is_none()
{
ans = Rc::clone(&left_aim);
}
left_aim = Rc::clone(&cur);
}
}
}
let mut curright = Rc::clone(&cur.borrow().as_ref().unwrap().right);
cur = Rc::clone(&curright);
}
return if !ans.borrow().is_none() {
ans
} else {
if !find_first(
Rc::clone(&left_aim.borrow().as_ref().unwrap().right),
Rc::clone(&o1),
Rc::clone(&o2),
)
.borrow()
.is_none()
{
Rc::clone(&left_aim)
} else {
Rc::clone(&head)
}
};
}
fn is_eq(mut a: Rc<RefCell<Option<TreeNode>>>, mut b: Rc<RefCell<Option<TreeNode>>>) -> bool {
if a.borrow().is_none() && b.borrow().is_none() {
return true;
}
if a.borrow().is_none() || b.borrow().is_none() {
return false;
}
return a.borrow().as_ref().unwrap().val == b.borrow().as_ref().unwrap().val;
} fn find_left_aim(
mut head: Rc<RefCell<Option<TreeNode>>>,
mut left_aim: Rc<RefCell<Option<TreeNode>>>,
) -> bool {
let mut tail = reverse_edge(head);
let mut cur = Rc::clone(&tail);
let mut ans = false;
while !cur.borrow().is_none() {
if is_eq(Rc::clone(&cur), Rc::clone(&left_aim)) {
ans = true;
}
let mut curright = Rc::clone(&cur.borrow().as_ref().unwrap().right);
cur = Rc::clone(&curright);
}
reverse_edge(tail);
return ans;
} fn reverse_edge(mut from: Rc<RefCell<Option<TreeNode>>>) -> Rc<RefCell<Option<TreeNode>>> {
let mut pre: Rc<RefCell<Option<TreeNode>>> = Rc::new(RefCell::new(None));
let mut next: Rc<RefCell<Option<TreeNode>>> = Rc::new(RefCell::new(None));
while !from.borrow().is_none() {
next = Rc::clone(&from.borrow().as_ref().unwrap().right);
{
let mut fromright = Rc::clone(&from.borrow().as_ref().unwrap().right);
fromright = Rc::clone(&pre); //此处错误
}
pre = Rc::clone(&from);
from = Rc::clone(&next);
}
return pre;
} fn find_first(
mut head: Rc<RefCell<Option<TreeNode>>>,
mut o1: Rc<RefCell<Option<TreeNode>>>,
mut o2: Rc<RefCell<Option<TreeNode>>>,
) -> Rc<RefCell<Option<TreeNode>>> {
if head.borrow().is_none() {
return Rc::new(RefCell::new(None));
}
let mut cur: Rc<RefCell<Option<TreeNode>>> = Rc::clone(&head);
let mut most_right: Rc<RefCell<Option<TreeNode>>> = Rc::new(RefCell::new(None));
let mut first: Rc<RefCell<Option<TreeNode>>> = Rc::new(RefCell::new(None));
while !cur.borrow().is_none() {
most_right = Rc::clone(&cur.borrow().as_ref().unwrap().left);
if !most_right.borrow().is_none() {
while !Rc::clone(&most_right.borrow().as_ref().unwrap().right)
.borrow()
.is_none()
&& !is_eq(
Rc::clone(&most_right.borrow().as_ref().unwrap().right),
Rc::clone(&cur),
)
{
let mut most_right_right = Rc::clone(&most_right.borrow().as_ref().unwrap().right);
most_right = Rc::clone(&most_right_right);
}
if Rc::clone(&most_right.borrow().as_ref().unwrap().right)
.borrow()
.is_none()
{
if !first.borrow().is_none()
&& (is_eq(Rc::clone(&cur), Rc::clone(&o1))
|| is_eq(Rc::clone(&cur), Rc::clone(&o2)))
{
first = Rc::clone(&cur);
} let mut most_right_right = Rc::clone(&most_right.borrow().as_ref().unwrap().right);
most_right_right = Rc::clone(&cur); //此处错误
let mut curleft = Rc::clone(&cur.borrow().as_ref().unwrap().left);
cur = Rc::clone(&curleft);
continue;
} else {
let mut most_right_right = Rc::clone(&most_right.borrow().as_ref().unwrap().right);
most_right_right = Rc::new(RefCell::new(None)); //此处错误
}
} else {
if first.borrow().is_none()
&& (is_eq(Rc::clone(&cur), Rc::clone(&o1))
|| is_eq(Rc::clone(&cur), Rc::clone(&o2)))
{
first = Rc::clone(&cur);
}
first = Rc::clone(&cur);
}
let mut curright = Rc::clone(&cur.borrow().as_ref().unwrap().right);
cur = Rc::clone(&curright);
}
return first;
}

执行结果如下:

答案用golang编写。代码如下:

package main

import "fmt"

func main() {
head := &TreeNode{val: 3}
head.left = &TreeNode{val: 5}
head.right = &TreeNode{val: 1}
head.left.left = &TreeNode{val: 6}
head.left.right = &TreeNode{val: 2}
ans := lowestCommonAncestor(head, head.left.left, head.left.right)
fmt.Println(ans.val)
} // Definition for a binary tree node.
type TreeNode struct {
val int
left *TreeNode
right *TreeNode
} // 提交以下的方法
// 该方法亮点在于:时间复杂度O(N),额外空间复杂度O(1)
func lowestCommonAncestor(head, o1, o2 *TreeNode) *TreeNode {
if findFirst(o1.left, o1, o2) != nil || findFirst(o1.right, o1, o2) != nil {
return o1
}
if findFirst(o2.left, o1, o2) != nil || findFirst(o2.right, o1, o2) != nil {
return o2
}
leftAim := findFirst(head, o1, o2)
cur := head
var mostRight *TreeNode
var ans *TreeNode
for cur != nil {
mostRight = cur.left
if mostRight != nil {
for mostRight.right != nil && mostRight.right != cur {
mostRight = mostRight.right
}
if mostRight.right == nil {
mostRight.right = cur
cur = cur.left
continue
} else {
mostRight.right = nil
if findLeftAim(cur.left, leftAim) {
if ans == nil && findFirst(leftAim.right, o1, o2) != nil {
ans = leftAim
}
leftAim = cur
}
}
}
cur = cur.right
}
if ans != nil {
return ans
} else {
if findFirst(leftAim.right, o1, o2) != nil {
return leftAim
} else {
return head
}
}
} func findLeftAim(head, leftAim *TreeNode) bool {
tail := reverseEdge(head)
cur := tail
ans := false
for cur != nil {
if cur == leftAim {
ans = true
}
cur = cur.right
}
reverseEdge(tail)
return ans
} func reverseEdge(from *TreeNode) *TreeNode {
var pre *TreeNode
var next *TreeNode
for from != nil {
next = from.right
from.right = pre
pre = from
from = next
}
return pre
} func findFirst(head, o1, o2 *TreeNode) *TreeNode {
if head == nil {
return nil
}
cur := head
var mostRight *TreeNode
var first *TreeNode
for cur != nil {
mostRight = cur.left
if mostRight != nil {
for mostRight.right != nil && mostRight.right != cur {
mostRight = mostRight.right
}
if mostRight.right == nil {
if first == nil && (cur == o1 || cur == o2) {
first = cur
}
mostRight.right = cur
cur = cur.left
continue
} else {
mostRight.right = nil
}
} else {
if first == nil && (cur == o1 || cur == o2) {
first = cur
}
}
cur = cur.right
}
return first
}

执行结果如下:


左神java代码

2022-05-22:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p的更多相关文章

  1. python、java实现二叉树,细说二叉树添加节点、深度优先(先序、中序、后续)遍历 、广度优先 遍历算法

    数据结构可以说是编程的内功心法,掌握好数据结构真的非常重要.目前基本上流行的数据结构都是c和c++版本的,我最近在学习python,尝试着用python实现了二叉树的基本操作.写下一篇博文,总结一下, ...

  2. JQuery 学习笔记-2017.05.22

    JQuery jQuery 是一个 JavaScript 函数库. jQuery 库包含以下特性: HTML 元素选取 HTML 元素操作 CSS 操作 HTML 事件函数 JavaScript 特效 ...

  3. 剑指offer18:操作给定的二叉树,将其变换为源二叉树的镜像。

    1 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像. 2 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ ...

  4. 用Java实现一个二叉树

    介绍 使用Java实现一个int值类型的排序二叉树 二叉树 二叉树是一个递归的数据结构,每个节点最多有两个子节点. 通常二叉树是二分查找树,每个节点它的值大于或者等于在它左子树节点上的值,小于或者等于 ...

  5. [Swift实际操作]八、实用进阶-(10)使用Swift创建一个二叉树BinaryTreeNode

    1.二叉树的特点: (1).每个节点最多有两个子树(2).左子树和右子树是有顺序的,次序不能颠倒(3).即使某节点只有一个子树,也要区分左右子树 2.二叉查找树(Binary Search Tree) ...

  6. 数据结构-用C++实现一个二叉树,递归方法中序遍历

    1:二叉排序树,又称二叉树.其定义为:二叉排序树或者空树,或者是满足如下性质的二叉树. (1)若它的左子树非空,则左子树上所有节点的值均小于根节点的值. (2)若它的右子树非空,则右子树上所有节点的值 ...

  7. 前、中、后序遍历随意两种是否能确定一个二叉树?理由? && 栈和队列的特点和区别

    前序和后序不能确定二叉树理由:前序和后序在本质上都是将父节点与子结点进行分离,但并没有指明左子树和右子树的能力,因此得到这两个序列只能明确父子关系,而不能确定一个二叉树. 由二叉树的中序和前序遍历序列 ...

  8. LeetCode 606. Construct String from Binary Tree (建立一个二叉树的string)

    You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...

  9. 查找常用字符(给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。)

    给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表. 例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 ...

  10. q次询问,每次给一个x,问1到x的因数个数的和。

    q次询问,每次给一个x,问1到x的因数个数的和. #include<cmath> #include<cstdio> #include<cstring> usingn ...

随机推荐

  1. springboot的websocket因IP问题无法连接

    首先遇到这个问题有点奇葩,出现在项目上线时的客户现场,头两天一直都无法确定原因,因为它的表现方式很奇怪,基于springboot实现的websocket,同样的代码在公司研发环境不会有问题,客户现场会 ...

  2. web初始:html记忆

    12.13html框架 <! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset ...

  3. 如何自动化测试你的接口?—— Rest Assured

    前言 不知道大家的项目是否都有对接口API进行自动化测试,反正像我们这种小公司是没有的.由于最近一直被吐槽项目质量糟糕,只能研发自己看看有什么接口测试方案.那么在本文中,我将探索如何使用 Rest A ...

  4. 使用 ApplicationContextAware 定义 SpringContextHolder 类

    需求:使用 @autowired注入一些对象,但发现不可以直接使用@Autowired,因为方法是static的,要使用该方法当前对象也必须是static,正常情况下@Autowired无法注入静态的 ...

  5. 为什么HashMap查找比List快很多?

    做两数之和这道题目时,引发了一个思考: 为什么两者运行时间相差如此之大???好残忍,我List比你HashMap到底差在哪**** 于是我一顿查资料.... 战犯哈希算法登场 哈希算法会根据你要存入的 ...

  6. Mybatis Plus根据某字段特定值排序

    需求 背景:一个审核流程.审核人等级分为市级和省级,管理员升级字段adminlevel,字段含义:1省级,2市级.审核字段audit为int字段,字段含义:1待市级审核,2待省级审核,3通过审核. 需 ...

  7. 3.HTTP协议

    HTTP协议 目录 HTTP协议 1.常见HTTP客户端 思考 1.网络协议为什么要分层? 2.www包含了哪些技术? 3.http请求/响应报文包含了哪些内容? 4.http特点有哪些? 2.代理的 ...

  8. 位运算符n&(n-1)详解与妙用

    用处一:求一个int类型数是否为2的幂 1.当n=4时,二进制为:0100 n-1=3,二进制为:0011 则:n&(n-1)==0  解释(将0100最右边的1变为0 则 0000=0) 2 ...

  9. selenium验证码处理-获取验证码图片二进流数据转成原图保存

    1.因为视频的作者给的代码不完整,只有核心部分的代码. 2.视频作者示例使用的第三方破解12306的脚本网页(失效了) 所以本人无法复现,此次截取部分代码作为理解核心意思(思想方法最重要) 1.面向对 ...

  10. 有一个公网IP地址

    这几天在家里拉了一条300M+的宽带,但是遇到了一些坑,本文就简单说明一下如下: 突发此次需求是这样的:阿里云有台服务器公网带宽是1M的,虽说带宽小,但是数据中心的服务器显然是稳定的,只是带宽太小,有 ...