반응형
1. 문제
- BST와 정수 key가 주어질 때, 해당 key를 제거한 BST를 반환하라.
2. 해결
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
if(!root) return null;
if(root.val === key) {
let childCount = 0;
if(root.left) childCount++;
if(root.right) childCount++;
if(childCount === 0) {
return null;
} else if(childCount === 1) {
return root.left || root.right;
} else if(childCount ===2) {
let successor = root.right;
while(successor.left) {
successor = successor.left;
}
root.val = successor.val;
root.right = deleteNode(root.right, successor.val)
return root;
}
}
if(root.val > key)root.left = deleteNode(root.left, key);
if(root.val < key)root.right = deleteNode(root.right,key)
return root;
};
- key와 일치하는 경우, 3가지 경우의 수를 나눠서 처리
- 삭제 대상 자식이 없는 경우,
- 삭제 대상 자식이 1개인 경우,
- 삭제 대상 자식이 2개인 경우,
- 여기서 2개인 경우는, 오른쪽 서브 트리의 최소값을 찾아 삭제 대상과 교체해줘야 BST가 깨지지 않는다.