450. Delete Node in a BST

2021-02-01  本文已影响0人  jluemmmm

删除 BST 中的指定元素,并维持二叉树的结构不变。

遍历,找到元素后:

时间复杂度 O(logN),空间复杂度O(H)

/**
 * 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} key
 * @return {TreeNode}
 */
var deleteNode = function(root, key) {
  if (!root) {
    return null;
  }
  if (root.val < key) {
    root.right = deleteNode(root.right, key)
  } else if (root.val > key) {
    root.left = deleteNode(root.left, key);
  } else {
    if (!root.left) return root.right;
    if (!root.right) return root.left;
    let ans = root;
    root = findPredecessor(ans.right);
    root.right = findSuccessor(ans.right);
    root.left = ans.left;
  }
  return root;
};

var findPredecessor = function(root) {
  if (!root.left) {
    return root;
  }
  return findPredecessor(root.left);
}

var findSuccessor = function(root) {
  if (!root.left) {
    return root.right;
  }
  root.left = findSuccessor(root.left);
  return root;
}
上一篇下一篇

猜你喜欢

热点阅读