# day20-binary tree-part07-7.22

1. 235.二叉搜索树的最近公共祖先

2. 701.二叉搜索树的插入操作

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

-------------------------------------------------------------------------

1. 235.二叉搜索树的最近公共祖先

In this practice, the solution is a bit different with the practice 236, which is caused by the feature of the binary search tree, i.e., the left tree node's val is less than the cur node while the right is bigger than it.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return root

if root.val > p.val and root.val > q.val:
left = self.lowestCommonAncestor(root.left, p, q)
if left:
return left

elif root.val < p.val and root.val < q.val:
right = self.lowestCommonAncestor(root.right, p, q)
if right:
return right

else:
return root


2. 701.二叉搜索树的插入操作

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
def constructBST(node, val):
if node is None:
return TreeNode(val)

if node.val > val:
node.left = constructBST(node.left, val)
else:
node.right = constructBST(node.right, val)

return node

return constructBST(root, val)

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

In this practice, the key point is to discuss all the terminate condition, then the following logic for recursive would be similar with the last practice 701.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return root

if root.val == key:
if root.left is None and root.right is None:
return None
elif root.left is None and root.right is not None:
return root.right
elif root.left is not None and root.right is None:
return root.left
else:
cur = root.right
while cur.left is not None:
cur = cur.left
cur.left = root.left
return root.right

if root.val > key:
root.left = self.deleteNode(root.left, key)
elif root.val < key:
root.right = self.deleteNode(root.right, key)

return root

• 22
点赞
• 4
收藏
觉得还不错? 一键收藏
• 0
评论
01-05 8331
03-01 1826
04-09 3万+
08-25 388
08-07 234
03-25 3409
09-26 1669
03-17 3148
05-04 3934
08-06 424
08-06 939
08-08 248

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。