算法错题集

95 阅读1分钟

450. 删除二叉搜索树中的节点 - 力扣(LeetCode)

二叉搜索树的删除时,找到删除节点,如果该节点的左或右子树为空,则子树直接上位,若都不为空,用左子树的最大值或者右子树的最小值代替

func deleteNode(root *TreeNode, key int) *TreeNode {
	if root == nil {
		return nil
	}
	if key < root.Val {
		root.Left = deleteNode(root.Left, key)
	} else if key > root.Val {
		root.Right = deleteNode(root.Right, key)
	} else if key == root.Val {
		//左或右子树为空直接上位
		if root.Left == nil {
			root = root.Right
		} else if root.Right == nil {
			root = root.Left
		} else {
			//右子树的最小值替代值
			nodeTree, val := swap(root.Right)
			if val != -1 {
				root.Right = nodeTree
				root.Val = val
			}
		}
	}
	return root
}
func swap(root *TreeNode) (*TreeNode, int) {
	if root == nil {
		return root, -1
	}
	if root.Left == nil {
		return root.Right, root.Val
	}
	var val int
	root.Left, val = swap(root.Left)
	return root, val
}