tasks for today:
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.二叉搜索树的插入操作
下一层将加入节点返回,本层用root->left或者root->right将其接住。
# 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