代码随想录刷题第二十三天
修剪二叉搜索树 (LC 669)
题目思路:
代码实现:
class Solution(object):
def trimBST(self, root, low, high):
"""
:type root: TreeNode
:type low: int
:type high: int
:rtype: TreeNode
"""
if root is None:
return None
if root.val > high:
if root.left is None and root.right is None:
return None
elif root.left is None and root.right is not None:
return None
else:
return self.trimBST(root.left, low, high)
elif root.val < low:
if root.left is None and root.right is None:
return None
elif root.left is not None and root.right is None:
return None
else:
return self.trimBST(root.right, low, high)
else:
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
将有序数组转换为平衡二叉树 (LC 108)
题目思路:
代码实现:
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
return None
mid = len(nums)//2
print(mid)
newnode = TreeNode(nums[mid])
left_list = nums[:mid]
right_list = nums[mid+1:]
newnode.left = self.sortedArrayToBST(left_list)
newnode.right = self.sortedArrayToBST(right_list)
return newnode
把二叉搜索树转换为累加数 (LC 538)
题目思路:
代码实现:
class Solution(object):
def __init__(self):
self.sum = 0
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is None:
return None
root.right = self.convertBST(root.right)
value = self.sum+root.val
root.val = value
self.sum = value
root.left = self.convertBST(root.left)
return root