
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
//先判断根节点是不是其中一个
if(root==p||root==q){
return root;
}
TreeNode leftRet=lowestCommonAncestor(root.left,p,q);
TreeNode rightRet = lowestCommonAncestor(root.right,p,q);
//开始判断,第一如果p,q在两边
if(leftRet!=null&&rightRet!=null){
return root;
}else if(leftRet!=null){
return leftRet;
}else if(rightRet!=null){
return rightRet;
}
//如果在左右子树中没找到
return null;
}
//栈实现
private boolean getPath(TreeNode root, TreeNode node, Deque<TreeNode> stack) {
// if(root==null||node==null)return false;
// stack.push(root);
// //放完之后 要检查
// if(root==node) return true;
// boolean ret1=getPath(root.left,node,stack);
// if(ret1) return true;
// boolean ret2= getPath(root.right,node,stack);
// if(ret2) return true;
// stack.pop();
// return false;
// }
// public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Deque<TreeNode> stack1= new LinkedList<>();
// getPath(root,p,stack1);
// Deque<TreeNode> stack2= new LinkedList<>();
// getPath(root,q,stack2);
// //判断栈的大小
// int size1=stack1.size();
// int size2=stack2.size();
//
// if(size1>size2){
// int size=size1-size2;
// while(size!=0){
// stack1.pop();
// size--;
// }
// }else{
// int size=size2-size1;
// while(size!=0){
// stack2.pop();
// size--;
// }
// }
// //栈里面数据的个数 是一样的
// while (!stack1.isEmpty()&&!stack2.isEmpty()){
// if(stack1.peek()!=stack2.peek()){
// stack1.pop();
// stack2.pop();
// }else{
// return stack1.peek();
// }
// }
// return null;
// }
文章介绍了如何在二叉树结构中,利用递归和栈的方法寻找两个给定节点的最低公共祖先。代码展示了如何通过遍历和比较两个栈来确定最近公共节点的位置。
875

被折叠的 条评论
为什么被折叠?



