처음에 while 사용해서 풀어보려 했는데 장황해졌다.
재귀적으로 접근하는게 코드 가독성이 좋다고 판단함
핵심은 지울 노드가 자식을 어떻게 가지고 있느냐에 따라 달라짐
만약 left, right 둘 다 있다면 이진 탐색 트리 특성 상 현재 root의 오른쪽 서브트리로부터 가장 작은 값을 root자리로 대치해야 함
root.left = child
or root.right = child
)class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else {
if (root.left == null) {
return root.right;
}
if (root.right == null) {
return root.left;
}
TreeNode minNode = findMin(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, minNode.val);
}
return root;
}
private TreeNode findMin(TreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}