不想搞的两天,摆烂的两天
# 代码随想录训练营第III期--022--python
# 235 二叉搜索树的最近公共祖先
class Solution:
def lowest(self, root,p,q):
ancestor = root
while True:
if ancestor.val > p.val and ancestor.val > q.val:
ancestor = ancestor.left
elif ancestor.val < p.val and ancestor.val < q.val:
ancestor = ancestor.right
else:
break
return ancestor
# 701
def insert(self, root, val):
if not root:
return TreeNode(val)
cur = root
while cur:
if val < cur.val:
if not cur.left:
cur.left = TreeNode(val)
break
else:
cur = cur.left
else:
if not cur.right:
cur.right = TreeNode(val)
break
else:
cur = cur.right
return root
# 450
def deleteNode(self, root, key):
if not root: return root
if root.val > key:
root.left = self.deleteNode(root.left, key)
return root
elif root.val < key:
root.right = self.deleteNode(root.right, key)
return root
else:
if not root.left:
return root.right
elif not root.right:
return root.left
else:
curr = root.right
while curr.left:
curr = curr.left
curr.left = root.left
return root.right
# =================================================
# 代码随想录训练营第III期--023--python
# 真实不想做二叉树了,做不动了,完全没想法
# 669
class Solution:
def trimBST(self, root, low, high):
if not root:
return None
if root.val < low:
right = self.trimBST(root.right, low, high)
return right
if root.val > high:
left = self.trimBST(root.left, low, high)
return left
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
# 108
# this question is quite interesting
def sortedArrayToBST(self, nums):
def build(left, right):
if left > right:
return
mid = left + (right - left) // 2
root = TreeNode(nums[mid])
root.left = build(left, mid - 1)
root.right = build(mid + 1, right)
return root
return build(0, len(nums) - 1)
# 538
pre = 0
def createBinaryTre(self, root):
if not root: return
self.createBinaryTre(root.right)
root.val += self.pre
self.pre = root.val
self.createBinaryTre(root.left)
def convertBST(self, root):
self.pre = 0
self. createBinaryTre(root)
return root