[JavaScript 刷题] 树 - 二叉搜索树中的插入操作, leetcode 701

[JavaScript 刷题] 树 - 二叉搜索树中的插入操作, leetcode 701

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:701. Insert into a Binary Search Tree

题目

如下:

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

解题思路

这一题题目中很明显的就提示说会接受所有的 BST 的构建方法,并且题目的规定也说题目并不会存在重复的数字,这里就挑最简单的方法区解题了。

二叉搜索树的做法就是比当所有的左子树的值会比当前结点的值小,所有的右子树的值都会比当前结点的值大,因此只要按照这个规律遍历到某个节点为空即可。

这种解法的平均时间复杂度为 O ( l o g ( n ) ) O(log(n)) O(log(n)),最差情况下,都是左子树/右子树的情况下会成为 O ( n ) O(n) O(n),因此进阶写法可以将其改为平衡二叉搜索树。

时间复杂度也可以理解成 O ( h ) O(h) O(h),其中 h h h 是树的高度。平衡二叉树规定左右子树的最大高度差不能超过 1,因此可以将时间复杂度限定在 O ( l o g ( n ) ) O(log(n)) O(log(n)) 值中。

这个实现方法不是最有效的,不过对我来说是最好理解的。

使用 JavaScript 解题

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} val
 * @return {TreeNode}
 */

//         61
//        /   \
//      46      66
//     /          \
//   43            88
//   /
// 39

var insertIntoBST = function (root, val) {
    
    
  const insert = (root) => {
    
    
    if (!root) return new TreeNode(val);

    if (!root.left && val <= root.val) return (root.left = new TreeNode(val));

    if (!root.right && val >= root.val) return (root.right = new TreeNode(val));

    if (val < root.val) insert(root.left);
    else insert(root.right);
  };

  const res = insert(root);

  return root || res;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125458856