일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- server
- nodeJS
- BinaryTree
- leetcode
- priority_queue
- 비트연산
- treenode
- array
- axios
- routes
- DP
- route
- MySQL
- state
- Context
- JSX
- css
- component
- c++
- node.js
- map
- UE5
- event
- Callback
- bit
- queue
- Navigation
- count
- React
- Props
- Today
- Total
우사미 코딩
[LeetCode] 450. Delete Node in a BST 본문
1. 문제링크
https://leetcode.com/problems/delete-node-in-a-bst
Delete Node in a BST - LeetCode
Can you solve this real interview question? 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 d
leetcode.com
2. key point
- Recursive로 문제를 해결할 수 있다
만약 key와 일치하는 node를 발견한 경우, 삭제할 위치에 올 node의 val을 왼쪽 오른쪽 subtree에서 찾아야한다.
만약 왼쪽 subtree에서 찾는 경우, 왼쪽 subtree의 가장 오른쪽에 있는 node가 가장 큰 값이 되기 때문에
왼쪽 subtree의 가장 높은 값으로 현재 root->val를 업데이트 해준다.
(오른쪽 subtree에서 찾는 경우 subtree의 가장 왼쪽에 있는 노드를 찾아서 root->val로 변경해줘야 함..! ㅇㅋ)
그리고 왼쪽 node는 재귀호출한다. 이 때 인자로 들어갈 key값을 위에서 변경해 준 root->val로 변경하는게 포인트!
3. solution
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return root;
if(root->val == key){
if(!root->left && !root->right)
return NULL;
if(!root->left || !root->right)
return root->left ? root->left : root->right;
TreeNode* temp = root->left;
while(temp->right)
temp = temp->right;
root->val = temp->val;
root->left = deleteNode(root->left, temp->val);
} else {
if(root->val > key)
root->left = deleteNode(root->left, key);
else
root->right = deleteNode(root->right, key);
}
return root;
}
};
'Leetcode' 카테고리의 다른 글
[Leetcode] 1143. Longest Common Subsequence (0) | 2023.06.22 |
---|---|
[Leetcode] 2090. K Radius Subarray Averages (0) | 2023.06.21 |
[Leetcode] 2542. Maximum Subsequence Score (0) | 2023.06.18 |
[Leetcode] 43. Multiply Strings (0) | 2023.05.28 |
[Leetcode] 322. Coin Change - DP (0) | 2023.05.28 |