File tree 2 files changed +49
-0
lines changed
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 262
262
442|[ Find All Duplicates in an Array] ( ./0442-find-all-duplicates-in-an-array.js ) |Medium|
263
263
443|[ String Compression] ( ./0443-string-compression.js ) |Medium|
264
264
448|[ Find All Numbers Disappeared in an Array] ( ./0448-find-all-numbers-disappeared-in-an-array.js ) |Easy|
265
+ 450|[ Delete Node in a BST] ( ./0450-delete-node-in-a-bst.js ) |Medium|
265
266
451|[ Sort Characters By Frequency] ( ./0451-sort-characters-by-frequency.js ) |Medium|
266
267
452|[ Minimum Number of Arrows to Burst Balloons] ( ./0452-minimum-number-of-arrows-to-burst-balloons.js ) |Medium|
267
268
456|[ 132 Pattern] ( ./0456-132-pattern.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 450. Delete Node in a BST
3
+ * https://leetcode.com/problems/delete-node-in-a-bst/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a root node reference of a BST and a key, delete the node with the given key in
7
+ * the BST. Return the root node reference (possibly updated) of the BST.
8
+ *
9
+ * Basically, the deletion can be divided into two stages:
10
+ * 1. Search for a node to remove.
11
+ * 2. If the node is found, delete the node.
12
+ */
13
+
14
+ /**
15
+ * Definition for a binary tree node.
16
+ * function TreeNode(val, left, right) {
17
+ * this.val = (val===undefined ? 0 : val)
18
+ * this.left = (left===undefined ? null : left)
19
+ * this.right = (right===undefined ? null : right)
20
+ * }
21
+ */
22
+ /**
23
+ * @param {TreeNode } root
24
+ * @param {number } key
25
+ * @return {TreeNode }
26
+ */
27
+ var deleteNode = function ( root , key ) {
28
+ if ( ! root ) return root ;
29
+ if ( root . val < key ) {
30
+ root . right = deleteNode ( root . right , key ) ;
31
+ } else if ( root . val > key ) {
32
+ root . left = deleteNode ( root . left , key ) ;
33
+ } else {
34
+ if ( root . left === null ) {
35
+ return root . right ;
36
+ } else if ( root . right === null ) {
37
+ return root . left ;
38
+ } else {
39
+ let node = root . right ;
40
+ while ( node . left ) {
41
+ node = node . left ;
42
+ }
43
+ node . left = root . left ;
44
+ return root . right ;
45
+ }
46
+ }
47
+ return root ;
48
+ } ;
You can’t perform that action at this time.
0 commit comments