LC450. 删除二叉搜索树中的节点
解题思路
只需要分类讨论就行,根据不同情况进行不同的处理
- 节点为空:return root
- 节点==val:
- 左右不为空:将要删除的节点的左树连接到右树的最左节点的左
- 左为空,右不为空:return root.right
- 左不为空,右为空:return root.left
- 节点>val:说明val在当前节点的左子树中
- 节点<val:说明val在当前节点的右子树中
代码
Python
1 | # Definition for a binary tree node. |
C++
1 | /** |
Go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func deleteNode(root *TreeNode, key int) *TreeNode {
if (root == nil) {return root}
if (root.Val == key) {
if (root.Left != nil && root.Right != nil) {
cur := root.Right
for cur.Left != nil {
cur = cur.Left
}
cur.Left = root.Left
return root.Right
} else if (root.Left == nil) {
return root.Right
} else if (root.Right == nil) {
return root.Left
}
} else if (root.Val > key) {
root.Left = deleteNode(root.Left, key)
} else if (root.Val < key) {
root.Right = deleteNode(root.Right, key)
}
return root
}
评论
