leetcode:#450. 删除二叉搜索树中的节点
题目详情
采用Java实现
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode deletedNode = root;
TreeNode deletedParentNode = null;
while (deletedNode != null && deletedNode.val != key) {
deletedParentNode = deletedNode;
if (deletedNode.val < key) {
deletedNode = deletedNode.right;
} else {
deletedNode = deletedNode.left;
}
}
if(notFoundTargetNode(deletedNode)) {
return root;
}
if (deletedNodeContainsLeftAndRightChildren(deletedNode)) {
TreeNode rightMinChildNode = deletedNode.right;
TreeNode rightMinChildNodeParent = deletedNode;
while (rightMinChildNode.left != null) {
rightMinChildNodeParent = rightMinChildNode;
rightMinChildNode = rightMinChildNode.left;
}
deletedNode.val = rightMinChildNode.val;
if (rightMinChildNodeParent.left == rightMinChildNode) {
rightMinChildNodeParent.left = rightMinChildNode.right;
} else {
rightMinChildNodeParent.right = rightMinChildNode.right;
}
return root;
}
TreeNode deletedNodeChild = getDeletedNodeSingleChild(deletedNode);
if (deletedParentNode == null) { // 删除根节点
root = deletedNodeChild;
} else if (deletedParentNode.left == deletedNode) {
deletedParentNode.left = deletedNodeChild;
} else {
deletedParentNode.right = deletedNodeChild;
}
return root;
}
private boolean deletedNodeContainsLeftAndRightChildren(TreeNode deletedNode) {
return deletedNode.left != null && deletedNode.right != null;
}
private boolean notFoundTargetNode(TreeNode deletedNode) {
return deletedNode == null;
}
private TreeNode getDeletedNodeSingleChild(TreeNode deletedNode) {
if (deletedNode.left != null) {
return deletedNode.left;
} else if (deletedNode.right != null) {
return deletedNode.right;
} else {
return null;
}
}
}