450.删除二叉搜索树中的节点

90 阅读1分钟

题目:
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。

一般来说,删除节点可分为两个步骤:

  1. 首先找到需要删除的节点;

算法: 1.root.Left = deleteNode() 2.分情况讨论

 func deleteNode(root *TreeNode, key int) *TreeNode {
	if root == nil {
		return nil
	}
	if key < root.Val {
		root.Left = deleteNode(root.Left, key)
	} else if root.Val < key {
		root.Right =  deleteNode(root.Right, key)
	} else {
		// root.Val == key
		// 左子树 = nil
		if root.Left == nil {
			return root.Right
		}
		// 右子树 = nil
		if root.Right == nil {
			return root.Left
		}
		// 左子树 != nil && 右子树 != nil
		node := root.Right
		for node.Left != nil {
			node = node.Left
		}
		node.Left = root.Left
		root = root.Right
	}
	
	return root
}