vals = [] helper(root) return '[' + ','.join(vals) + ']' def deserialize(data): def helper(root): val = next(vals) if val == '#': return None root = Node(int(val)) root.left = helper(root) root.right = helper(root) return root vals = iter(data[1:-1].split(',')) return helper(root) root = Node("1") root.left = Node("2") root.left.left = Node('6') root.right = Node("3") data = serialize(root) print(data) deserialized_root = deserialize(data) from BaseBST import printTree printTree(deserialized_root)
from BaseBST import genTree, printTree def mergeTrees(t1, t2): if not t1 and not t2: return None if not t2: return t1 if not t1: return t2 t1.val += t2.val t1.left = mergeTrees(t1.left, t2.left) t1.right = mergeTrees(t1.right, t2.right) return t1 t1 = genTree("[1,3,2,5]") t2 = genTree("[2,1,3,null,4,null,7]") printTree(mergeTrees(t1, t2))
from BaseBST import printTree, TreeNode # The root is the maximum number in the array # The left subtree is the maximum tree constructed from left part subarray divided by the maximum number # The right subtree is the maximum tree constructed from right part subarray divided by the maximum number def constructMaximumBinaryTree(nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None maxNum = max(nums) # Finding the max in list to construct root maxIndex = nums.index( maxNum ) #Finding index in order to form left list for left subtree and right list for right subtree root = TreeNode(maxNum) # forming the root root.left = constructMaximumBinaryTree( nums[:maxIndex] ) #left subtree constructed from left elements of root element root.right = constructMaximumBinaryTree( nums[maxIndex + 1:]) # right subtree from right elements of root element return root nums = [3, 2, 1, 6, 0, 5] printTree(constructMaximumBinaryTree(nums))
#700. https://leetcode.com/problems/search-in-a-binary-search-tree/description/ from BaseBST import genTree, printTree def searchBST(root, target): if not root: return [] if root.val == target: # if root equals the target, return the root return root if target < root.val: # if target < root, search in its left subtree return searchBST(root.left, target) else: return searchBST( root.right, target) # if target > root, search in its right subtree root = genTree("[4, 2, 7, 1, 3, null, null]") printTree(searchBST(root, 2))
if not root: return None root.left = pruneTree(root.left) root.right = pruneTree(root.right) if root.val == 1: return root if root.val == 0: if not root.left and not root.right: return None return root root = genTree('[1,0,1,0,0,0,1]') printTree(pruneTree(root)) # # # # if not root: return None # node = root # def containsOne(node): # if node.val == 0 and (pruneTree(node.left) != 1 or pruneTree(node.right) != 1): # return False # return True # # if not containsOne(node.left) and not containsOne(node.right): # return None
from BaseBST import genTree, printTree from collections import deque def invertTreeRecursive(root): if not root: return None root.right, root.left = invertTreeRecursive(root.left), invertTreeRecursive(root.right) return root def invertTreeBFS(root): if not root: return None queue = deque([root]) while queue: node = queue.popleft() if node: node.left, node.right = node.right, node.left if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root root = genTree('[4,2,7,1,3,6,9]') # printTree(invertTreeRecursive(root)) printTree(invertTreeBFS(root))
# https://leetcode.com/problems/insert-into-a-binary-search-tree/description/ from BaseBST import genTree, printTree, TreeNode # if there is no root, then just return the node of the given value # Using recursion, check if the val is less than or greater than each node and according add it as a left or right node def insertIntoBST(root, val): if not root: return TreeNode(val) if val < root.val: root.left = insertIntoBST(root.left, val) if val > root.val: root.right = insertIntoBST(root.right, val) return root root = genTree('[4,2,7,1,3]') printTree(insertIntoBST(root, 5))
# https://leetcode.com/problems/trim-a-binary-search-tree/ from BaseBST import genTree, printTree # if root is less than the left range value, then we pass the root and its left subtree and trim from the right node onwards # if root is greater than the right range value, then we pass the root and its right subtree and trim from the left node onwards # repeat this until there is no node and then return the root def trimBST(root, L, R): def trim(root): if not root: return None if root.val < L: return trim(root.right) elif root.val > R: return trim(root.left) else: root.left = trim(root.left) root.right = trim(root.right) return root return trim(root) root = genTree('[3,0,4,null,2,null,null,1]') printTree(trimBST(root, 1, 3))
# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ from BaseBST import TreeNode, printTree # 1.Since the given list is sorted, we can choose the middle element to be root node # 2. Then the list elements to the left of the middle element will be lesser and can form the left subtree # 3. All the list elements to the right of the middle element will be greater and can form the right subtree # 4. Form the left subtree from leftList and right tree from rightList # 5. Call the function recursively until there are no elements left def SortedToBST(nums): if nums == []: return None middle = len(arr) // 2 root = TreeNode(nums[middle]) leftList = nums[:middle] rightList = nums[middle + 1:] if leftList: root.left = SortedToBST(leftList) if rightList: root.right = SortedToBST(rightList) return root printTree(SortedToBST([-10, -3, 0, 5, 9]))