701. 二叉搜索树中的插入操作

深度优先搜索

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {

        if (root == null){
            return new TreeNode(val);
        }

        if (root.val > val){

            root.left = insertIntoBST(root.left, val);
            return root;
        }
        else {
            root.right = insertIntoBST(root.right, val);
            return root;
        }
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

迭代

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {

        if (root == null){
            return new TreeNode(val);
        }

        /**
         * 插入元素需要用到父节点,因此用prev指针指向父节点
         */
        TreeNode newRoot = root;
        TreeNode prev = null;

        while (root != null){

            prev = root;

            if (root.val > val){
                root = root.left;
            }
            else {
                root = root.right;
            }
        }

        if (prev.val > val){
            prev.left = new TreeNode(val);
        }
        else {
            prev.right = new TreeNode(val);
        }

        return newRoot;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/

posted @ 2022-02-24 11:42  振袖秋枫问红叶  阅读(35)  评论(0)    收藏  举报