Leetcode-0419

1644. 二叉树的最近公共祖先 II(中等)

问题:没有想到单独判断点是否存在,判断不能在递归里进行,因为有的枝单独存在一个点。需要单独写了个函数。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(exist(root,p)&&exist(root,q))return find(root,p,q);
        return null;
    }

    public TreeNode find(TreeNode root, TreeNode p, TreeNode q){
        if(root==null)return null;
        TreeNode left = find(root.left,p,q);
        TreeNode right = find(root.right,p,q);
        if(left!=null&&right!=null)return root;
        else if(root==p||root==q)return root;
        return left==null?right:left;
    }

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

1676. 二叉树的最近公共祖先 IV(中等)

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
        if(root == null)return null;
        TreeNode left = lowestCommonAncestor(root.left,nodes);
        TreeNode right = lowestCommonAncestor(root.right,nodes);
        if(left!=null&&right!=null)return root;
        for(int i=0;i<nodes.length;i++)
            if(nodes[i]==root)return root;
        return left==null?right:left;
    }
}

704. 二分查找(简单)

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while(left<=right){
            int mid = (left+right)/2;
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]<target){
                left = mid+1;
            }else {
                right = mid - 1;
            }
        }
        return -1;
    }
}

1650. 二叉树的最近公共祖先 III(中等)

//	mine
class Solution {
    public Node lowestCommonAncestor(Node p, Node q) {
        
        while(p!=q){
            if(exist(p,q))return p;
            else if(exist(q,p))return q;
            p = p.parent;
            q = q.parent;
        }
        return p;
    }

    public boolean exist(Node root,Node t){
        if(root == null)return false;
        if(root == t)return true;
        return exist(root.left,t)||exist(root.right,t);
    }
}

//	npy's
class Solution {
    public Node lowestCommonAncestor(Node p, Node q) {
        Set<Node> set = new HashSet<>();
        while (p != null) {
            set.add(p);
            p = p.parent;
        }
        while (q != null) {
            if(set.contains(q)) return q;
            q = q.parent;
        }
        return null;
    }
}

35. 搜索插入位置(简单)

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        while(left<right){
            int mid = left + (right-left)/2;
            //  这是lowerBound写法,如果是upperbound写法,就把这个换成<=
            if(nums[mid]<target)left = mid+1;
            else right = mid;
        }
        return right;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,数据结构)