450. 删除二叉搜索树中的节点
1.题目描述及示例
-
题目描述
-
示例
2.题解思路及代码
- 思路
设root为要删除的节点,用先序遍历。
如果root为叶子节点,返回null。
如果root的左孩子不空,找到root的左子树的最大值所在的节点l,让l的右孩子指向root的右子树。最后,返回root的左孩子。
如果root的右孩子不空,找到root的右子树的最小值所在的节点r,让r的左孩子指向root的左子树。最后,返回root的右孩子。
- 代码
public TreeNode deleteNode(TreeNode root, int key) {
return preOrder(root,key);
}
TreeNode preOrder(TreeNode root,int key)
{
if (root!=null)
{
if (root.val==key)
{
if (root.left==null&&root.right==null)
return null;
else if (root.left!=null)
{
TreeNode p=root.left;
while (p.right!=null)
p=p.right;
p.right=root.right;
root.right=null;
return root.left;
}
else if (root.right!=null)
{
TreeNode p=root.right;
while (p.left!=null)
p=p.left;
p.left=root.left;
root.left=null;
return root.right;
}
}
root.left=preOrder(root.left,key);
root.right=preOrder(root.right,key);
}
return root;
}