235.二叉搜索树最近公共祖先701.二叉搜索树插入操作

72 阅读1分钟

235.二叉搜索树最近公共祖先

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //如果p和q位于这个节点两端,那么这个节点为最近公共祖先
        if((long)(root.val - p.val) * (long)(root.val - q.val) <= 0) return root;
        //向左找 or 向右找
        return lowestCommonAncestor(p.val < root.val ? root.left : root.right, p, q);
    }
}

701.二叉搜索树插入操作

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) return new TreeNode(val);
        if(val < root.val){
            root.left = insertIntoBST(root.left, val);
        }else if(val > root.val){
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}