美文网首页
701. Insert into a Binary Search

701. Insert into a Binary Search

作者: jluemmmm | 来源:发表于2021-11-22 12:48 被阅读0次

给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

递归

  • Runtime: 116 ms, faster than 93.11%
  • Memory Usage: 46.8 MB, less than 89.20%
  • 时间复杂度O(n),空间复杂度O(n)
/**
 * 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}
 */
var insertIntoBST = function(root, val) {
  if (!root) {
    return new TreeNode(val);
  }
  if (val > root.val) {
    root.right = insertIntoBST(root.right, val);
  } else {
    root.left = insertIntoBST(root.left, val);
  }
  return root;
};

迭代

  • Runtime: 120 ms, faster than 84.82%
  • Memory Usage: 47.2 MB, less than 51.80%
  • 时间复杂度O(n),空间复杂度O(n)
var insertIntoBST = function(root, val) {
  if(!root) {
    return new TreeNode(val);
  }
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    if (node) {
      if (val > node.val) {
        if (node.right) queue.push(node.right);
        else node.right = new TreeNode(val);
      } else {
        if (node.left) queue.push(node.left);
        else node.left = new TreeNode(val);
      }
    }
  }
  return root;
};

相关文章

网友评论

      本文标题:701. Insert into a Binary Search

      本文链接:https://www.haomeiwen.com/subject/gwpmtrtx.html