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 := headlet mut cur: Option<Rc<RefCell<TreeNode>>> = Some(Rc::clone(&head.as_ref().unwrap()));//var most_right *TreeNodelet mut most_right: Option<Rc<RefCell<TreeNode>>> = None;//var first *TreeNodelet 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 mainimport "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   intleft  *TreeNoderight *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 := headvar mostRight *TreeNodevar ans *TreeNodefor cur != nil {mostRight = cur.leftif mostRight != nil {for mostRight.right != nil && mostRight.right != cur {mostRight = mostRight.right}if mostRight.right == nil {mostRight.right = curcur = cur.leftcontinue} else {mostRight.right = nilif 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 := tailans := falsefor cur != nil {if cur == leftAim {ans = true}cur = cur.right}reverseEdge(tail)return ans
}func reverseEdge(from *TreeNode) *TreeNode {var pre *TreeNodevar next *TreeNodefor from != nil {next = from.rightfrom.right = prepre = fromfrom = next}return pre
}func findFirst(head, o1, o2 *TreeNode) *TreeNode {if head == nil {return nil}cur := headvar mostRight *TreeNodevar first *TreeNodefor cur != nil {mostRight = cur.leftif 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 = curcur = cur.leftcontinue} 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. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先

    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 三种情况: 1).如果左边为空,右边不为空,则右边的第一个节点就为公共祖先 2).如果右边为空,左边不为空,则左边的第一个节点就为公共祖先 3) ...

  2. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

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

  3. Java 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先

    代码中的二叉树长这个样子↓↓↓ 找到该树中两个指定节点的最近公共祖先,有三种情况,如图: import java.util.*; import java.util.Queue; //下面的所有求结点总 ...

  4. 【每周Java技术】2022.05.16 周一 ~ 2022.05.22 周日(Srping Boot | 二叉树 | Docker | 微服务/云原生)

    文章目录 01. 05.16 周一 1.1)Spring Boot 1.1.1) Spring Boot的组成部分 1.1.2) 了解自动配置的实现原理 1.2)数组降序 02. 05.19 周四 1 ...

  5. 常考数据结构与算法----给定一个二叉树和一个值 sum,请找出所有的根节点到叶子节点的节点值之和等于sum 的路径,

    题目描述 给定一个二叉树和一个值sum,请找出所有的根节点到叶子节点的节点值之和等于sum 的路径, 例如: 给出如下的二叉树,sum=22, 返回 [ [5,4,11,2], [5,8,9] ] 示 ...

  6. java二叉树镜像_给定一个二叉树,检查它是否是镜像对称的。

    原题 给定一个二叉树,检查它是否是镜像对称的. 原理 以根节点划分中心线,检查是否镜像对称. 一个指向从左节点出发,一个节点从右节点出发比较. 左节点的左孩子和右节点的右孩子比较 左节点的右孩子和右节 ...

  7. 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

    给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树. 有效 二叉搜索树定义如下: 节点的左子树只包含 小于 当前节点的数. 节点的右子树只包含 大于 当前节点的数. 所有左子树和右子 ...

  8. Java黑皮书课后题第8章:*8.23(游戏:找到翻转的单元格)假定给定一个填满0和1的6*6矩阵,所有的行和列都有偶数个1。让用户翻转一个单元,编写一个程序找到哪个单元格被翻转了

    *8.23(游戏:找到翻转的单元格)假定给定一个填满0和1的6*6矩阵,所有的行和列都有偶数个1.让用户翻转一个单元,编写一个程序找到哪个单元格被翻转了 题目 题目描述与运行示例 破题 代码 题目 题 ...

  9. LeetCode 刷题之旅(2020.05.22)——105. 从前序与中序遍历序列构造二叉树(中)

    LeetCode 刷题之旅(2020.05.22)--105. 从前序与中序遍历序列构造二叉树(中) 题目: 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如, ...

最新文章

  1. Ubuntu + VirtualBox + windows xp互相访问
  2. spring+cxf 开发webService(主要是记录遇到spring bean注入不进来的解决方法)
  3. mysql查询当天所有数据sql语句
  4. Extjs关于alert显示不出—异步问题
  5. Wireshark 抓包分析 RTSP/RTP/RTCP 基本工作过程
  6. 一起谈.NET技术,异步调用与多线程的区别
  7. mysql创建表时添加范式_MySql三大范式与数据库设计和表创建常用语句
  8. b站电脑客户端_B站(哔哩哔哩) 视频批量下载工具#电脑版##更新
  9. Java编写简单密码问题
  10. vscode自定义HTML、vue等模板内容(一个、多个)- 教程篇
  11. Linux笔试题及答案
  12. 几种常见模式识别算法整理和总结【转】
  13. android 去广告浏览器,手机去广告浏览器Adblock Plus Browser
  14. RFM用户分层模型|原理+Python全流程实现
  15. 作业中关于H5中动画的实现——animation
  16. SEO主要是做什么的?零基础能学习吗?
  17. [生存志] 第43节 齐文姜齐宣姜争艳
  18. 自动驾驶车载相机rosenberger接口防呆设计
  19. 结构方程模型的建立、拟合、评估、筛选和结果展示全过程
  20. Access Token机制简单介绍

热门文章

  1. 稀疏矩阵的压缩存储与操作(实测程序)
  2. tar 排除指定的目录 ,或者指定文件类型
  3. 如何缩小安全漏洞爆炸半径,实现服务间零信任安全?
  4. 越来越热的眼镜,苹果为什么不做 | 今夜科技谈
  5. C语言初学者-计算器(不奥深,基础,嘿嘿)
  6. 关闭shift+ctrl+f繁体字切换
  7. ubuntu时间差八小时
  8. 基于SSM的在线音乐网站开发与实现
  9. 怎样恢复移动硬盘的数据
  10. 【Kivy自学笔记】Python开发App必备!Kivy打包exe文件!(补充:设置Kivy应用logo导入kv文件)