算法修炼Day22|● 235. 二叉搜索树的最近公共祖先 ● 701.二叉搜索树中的插入操作 ● 450.删除二叉搜索树中的节点

69 阅读1分钟

LeetCode:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)

1.思路

首先,不用做判空处理了, 三种情况,当前节点值大于p和q,向左遍历;当前节点值小于p和q,向右遍历;分别返回对应的左右节点进行递归判断。③介于p和q之间的(包含p和q)直接返回当前节点即可。

2.代码实现
/**
 * 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) {
        
        if (root.val > p.val && root.val > q.val) {
            TreeNode left = lowestCommonAncestor(root.left, p, q);
            return left;
        }
        if (root.val < p.val && root.val < q.val) {
            TreeNode right = lowestCommonAncestor(root.right, p, q);
            return right;
        }
        return root;
    }
}

3.复杂度分析

时间复杂度:O(logn).

空间复杂度:O(logn).

LeetCode:

1.思路

当前节点值与传入值比较,root.val>val,向右遍历;否则向左遍历,直到root为null时创建叶子节点传入目标值,返回root.

2.代码实现
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);

        if (root.val > val) {
            // if (root.left == null) {
            //     root.left = new TreeNode(val);
            //     return root;
            // }
            root.left = insertIntoBST(root.left, val);
        }
        if (root.val < val) {
            // if (root.right == null) {
            //     root.right = new TreeNode(val);
            //     return root;
            // }
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}
3.复杂度分析

时间复杂度:O(logn).

空间复杂度:O(logn);

LeetCode:

1.思路

分情况讨论,当节点不存在时,返回root,当节点左子树为空(返回右子树)/当节点右子树为空(返回左子树)/当节点左右子树均不为空(右子树顶上,左子树赋予到右子树左叶子节点或者左子树顶上,右子树放在左子树右叶子节点)。

2.代码实现
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return root;
        if (root.val == key) {
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            } else {
                TreeNode cur = root.right;
                while (cur.left != null) {
                    cur = cur.left;
                }
                cur.left = root.left;
                root = root.right;
                return root;
            }
        }
        if (root.val > key) root.left = deleteNode(root.left, key);
        if (root.val < key) root.right = deleteNode(root.right, key);
        return root;
    }
}
3.复杂度分析

时间复杂度:O(logn).

空间复杂度:O(logn).