235. 二叉搜索树的最近公共祖先
从根节点向下遍历,第一次遇到cur节点在[p,q]之间,则cur节点就是p和q的最近公共祖先
# 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':
return self.traversal(root, p, q)
def traversal(self, cur: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not cur:
return None
if cur.val > p.val and cur.val > q.val:
left = self.traversal(cur.left, p, q)
if left:
return left
if cur.val < p.val and cur.val < q.val:
right = self.traversal(cur.right, p, q)
if right:
return right
return cur
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 __init__(self):
self.parent = None
def traversal(self, cur, val):
if cur is None:
node = TreeNode(val)
if val > self.parent.val:
self.parent.right = node
else:
self.parent.left = node
return
self.parent = cur
if cur.val > val:
self.traversal(cur.left, val)
if cur.val < val:
self.traversal(cur.right, val)
def insertIntoBST(self, root, val):
self.parent = TreeNode(0)
if root is None:
return TreeNode(val)
self.traversal(root, val)
return root
450.删除二叉搜索树中的节点
删除节点比前一个题插入节点要难,因为要调整树的结构
# 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, key):
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: #只有右节点,返回右节点
return root.right
elif 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)
if root.val < key:
root.right = self.deleteNode(root.right, key)
return root
参考文档:代码随想录