236.二叉搜索树的公共祖先

文章讲述了在二叉树中寻找两个节点的公共祖先问题,介绍了两种方法:一种是使用栈来对齐节点路径,另一种是递归与简化代码的理解。后者虽然时间复杂度稍高,但易于理解。
摘要由CSDN通过智能技术生成

236.二叉树的公共祖先

思路

看到题想的是找到两个点的各自路径利用stack保存,根据路径长度大小将两个stack的值对齐到同一层,之后同时出栈节点,若相同则找到祖先节点。但是效率不高

看了大佬代码,递归思想很难理解。

根据大佬代码思想写了一个便于理解的版本,分为四种情况,递归求解。

代码

简单方法

    Stack<TreeNode> stack=new Stack<>();

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
       int deep_p=findDeep(root,p,1);
       Stack<TreeNode> stack_p=new Stack<>();
       stack_p.addAll(stack);
       stack.clear();
       int deep_q=findDeep(root,q,1);
       Stack<TreeNode> stack_q=new Stack<>();
       stack_q=stack;

        //将p作为长端
       if (deep_p<deep_q){
           int temp;Stack<TreeNode> stack1=new Stack<>();
           temp=deep_q;stack1.addAll(stack_q);stack_q.clear();
           deep_q=deep_p;stack_q.addAll(stack_p);stack_p.clear();
           deep_p=temp;stack_p.addAll(stack1);
       }

       while (deep_p>deep_q){
           stack_p.pop();
           deep_p--;
       }
       TreeNode node_q=stack_q.pop(),node_p=stack_p.pop();
       while (node_q!=node_p){
           node_q=stack_q.pop();
           node_p=stack_p.pop();
       }
       return node_q;
    }
    public int findDeep(TreeNode root,TreeNode node,int deep){
        stack.push(root);
        if (root==null) return 0;
        if (root==node) return deep;
        int left=findDeep(root.left,node,deep+1);
        if (left==0) stack.pop();
        int right=findDeep(root.right,node,deep+1);
        if (right==0) stack.pop();
      return   Math.max(left,right);
    }


大佬代码(比较难懂,O(n))

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null) return right;
        if(right == null) return left;
        return root;
    }
}


思想简化代码(O(4*n),多了4次find)

public class Solution {


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if (root==null) return null;
            if (p==root || q==root) return root;//第一种情况,p,q其中一个为祖先节点
            if (find(root.left,p) && find(root.left,q)){ //第二种情况,p,q在当前节点左侧
                return lowestCommonAncestor(root.left,p,q);
            }
            if (find(root.right,p) && find(root.right,q)){//第三种情况,p,q在当前节点右侧
                return lowestCommonAncestor(root.right,p,q);
            }
            //第四种情况,p,q在两边
            return root;

    }
    public boolean find(TreeNode root,TreeNode p){
        if (root==null) return false;
        if (root==p) return true;
        return find(root.left,p) || find(root.right,p);
    }

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉搜索树(Binary Search Tree,简称BST)是一种特殊的二叉树,它的每个节点的值都大于其左子树中的所有节点的值,且小于其右子树中的所有节点的值。最近公共祖先(Lowest Common Ancestor,简称LCA)是指在二叉树中,两个节点p和q的最近公共祖先节点。 对于给定的二叉搜索树,我们可以通过比较节点的值来确定最近公共祖先节点。具体步骤如下: 1. 从根节点开始遍历二叉搜索树。 2. 如果当前节点的值大于p和q的值,说明p和q都在当前节点的左子树中,因此继续遍历当前节点的左子树。 3. 如果当前节点的值小于p和q的值,说明p和q都在当前节点的右子树中,因此继续遍历当前节点的右子树。 4. 如果当前节点的值介于p和q的值之间,说明当前节点就是最近公共祖先节点。 以下是一个示例代码,演示了如何找到二叉搜索树的最近公共祖先节点: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def lowestCommonAncestor(root, p, q): if root.val > p.val and root.val > q.val: return lowestCommonAncestor(root.left, p, q) elif root.val < p.val and root.val < q.val: return lowestCommonAncestor(root.right, p, q) else: return root # 创建一个二叉搜索树 root = TreeNode(6) root.left = TreeNode(2) root.right = TreeNode(8) root.left.left = TreeNode(0) root.left.right = TreeNode(4) root.right.left = TreeNode(7) root.right.right = TreeNode(9) root.left.right.left = TreeNode(3) root.left.right.right = TreeNode(5) # 找到节点3和节点5的最近公共祖先 p = TreeNode(3) q = TreeNode(5) lca = lowestCommonAncestor(root, p, q) print("最近公共祖先节点的值为:", lca.val) # 输出:2 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值