Skip to content

Latest commit

 

History

History
71 lines (48 loc) · 1.76 KB

0450-delete-node-in-a-bst.adoc

File metadata and controls

71 lines (48 loc) · 1.76 KB

450. Delete Node in a BST

{leetcode}/problems/delete-node-in-a-bst/[LeetCode - Delete Node in a BST^]

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.

  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7

思路分析

一、递归

  1. 根据二叉搜索树的特性,逐步递归去寻找要删除的节点。

  2. 找到后,有几种情况要处理:

    1. 如果是叶子节点,则直接返回 null。

    2. 如果没有左树或右树,那么把右树或者左树返回接口

    3. 如果同时有左右树,那么在左树上找到最右节点或者在右树上找到最左节点,然后将其删除。把原来的左右树对接到寻找到的节点的左右树上,返回找到的那个节点即可。

link:{sourcedir}/_0450_DeleteNodeInABST.java[role=include]

二、迭代

迭代就需要注意了:要找到删除节点的父节点(否则没版本处理。)