刷题小记 (10) LeetCode 235 二叉搜索树的最近公共祖先

LeetCode 235

2020.8.14

我的通过代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        List<TreeNode> list_left = new ArrayList<TreeNode>();
        List<TreeNode> list_right = new ArrayList<TreeNode>();
        traverse(root,list_left,p.val);
        traverse(root,list_right,q.val);
        boolean flag = false;
        for(int i=list_left.size()-1;i>=0;i--) {
            for(int j=list_right.size()-1;j>=0;j--) {
                if(list_left.get(i)==list_right.get(j)) {
                    root = list_right.get(j);
                    flag = true;
                    break;
                }
            }
            if(flag) break;
        }
        return root;
    }

    void traverse(TreeNode root, List<TreeNode> list, int a) {
        if(root==null) return;
        if(root.val==a) list.add(root);
        if(root.val>a) {
            list.add(root);
            traverse(root.left,list,a);
        }
        if(root.val<a) {
            list.add(root);
            traverse(root.right,list,a);
        }
    }

}

过于暴力,不太好。
二叉搜索树真是一种非常方便的树,左小右大,且任一棵子树也是二叉搜索树。

官方题解

算法描述:
1.从根节点开始遍历树
2.如果节点 p 和节点 q 都在右子树上,那么以右孩子为根节点继续 1 的操作
3.如果节点 p 和节点 q 都在左子树上,那么以左孩子为根节点继续 1 的操作
4.如果条件 2 和条件 3 都不成立,这就意味着我们已经找到节 p 和节点 q 的 LCA 了

代码如下:

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        // Value of current node or parent node.
        int parentVal = root.val;

        // Value of p
        int pVal = p.val;

        // Value of q;
        int qVal = q.val;

        if (pVal > parentVal && qVal > parentVal) {
            // If both p and q are greater than parent
            return lowestCommonAncestor(root.right, p, q);
        } else if (pVal < parentVal && qVal < parentVal) {
            // If both p and q are lesser than parent
            return lowestCommonAncestor(root.left, p, q);
        } else {
            // We have found the split point, i.e. the LCA node.
            return root;
        }
    }
}

上述内容转自LeetCode
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solution/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian–2/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值