LeetCode.1008.二叉树的公共祖先

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;
//    }

  • 15
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值