def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return TreeNode(val) if val > root.val: root.right = self.insertIntoBST(root.right, val) else: root.left = self.insertIntoBST(root.left, val) return root
# def inorderTraversalTest(root: TreeNode) -> List[int]: # stack, res = [root], [] # # 中序是先左后中后右 # while stack: # temp = stack.pop() # if temp: # if temp.left: # stack.append(temp.left) # res.append(temp.left.val) # if temp.right: # stack.append(temp.right) # res.append(temp.val) # return res if __name__ == '__main__': tree = TreeNode(6) tree.left = TreeNode(8) tree.right = TreeNode(4) # tree.left.left = TreeNode(9) # tree.left.right = TreeNode(7) # tree.right.left = TreeNode(5) # tree.right.right = TreeNode(3) print(bfs(tree)) print("---------") print(dfs(tree)) print('---------') print(f'inorder is {inorderTraversal(tree)}') print(f'dfs preorder is {dfsPreorder(tree)}') print(f'dfs postorder is {dfsPostorder(tree)}') # print(f'inorderTravsalTest is {inorderTraversalTest(tree)}')
from base.tree.tree_node import TreeNode class Solution: def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: if root is None: return None if root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root if left is None and right is None: return None if left is None: return right else: return left if __name__ == '__main__': root = [6, 2, 8, 0, 4, 7, 9, None, None, 3, 5] p = 2 q = 8 tree = TreeNode.from_list(root) print(tree)
class Solution: def isUnivalTree(self, root: TreeNode) -> bool: res = [] def dfs(root): queue = [root] while queue: element = queue.pop(0) res.append(element.val) if element.left: dfs(root.left) if element.right: dfs(root.right) dfs(root) return len(set(res)) == 1 if __name__ == '__main__': sol = Solution() tree = TreeNode.from_list([ 2, 2, 2, 2, 5, ]) print(tree) print(sol.isUnivalTree(tree))
from base.tree.tree_node import TreeNode class Solution: def convertBST(self, root: TreeNode) -> TreeNode: pass if __name__ == '__main__': a = TreeNode.from_list( [4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8]) sol = Solution() print(sol.convertBST(a))
# Definition for a binary tree node. from base.tree.tree_node import TreeNode class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: pass if __name__ == '__main__': b = [5, 3, 6, 2, 4, None, 7] t = TreeNode.from_list(b) print(t)
from base.tree.tree_node import TreeNode class Solution: # TODO def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: pass if __name__ == '__main__': root1 = TreeNode() root2 = TreeNode() sol = Solution() print(sol.mergeTrees(root1, root2))
from base.tree.tree_node import TreeNode class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: level_values, queue = [], [root] while queue: next_level, curr_vals = [], [] for i in queue: if i.val is not None: curr_vals.append(i.val) if i.left: next_level.append(i.left) if i.right: next_level.append(i.right) queue = next_level level_values = curr_vals return level_values[0] if __name__ == '__main__': tree = TreeNode.from_list([2, 1, 3]) sol = Solution() print(sol.findBottomLeftValue(tree))
if root is None: return 0 result, queue = [], [root] while queue: next_level, vals = [], [] for node in queue: if node.val is not None: vals.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) queue = next_level result.append(vals) odd = 0 even = 0 for i, v in enumerate(result): if i % 2 == 0: even += sum(v) else: odd += sum(v) return max(odd, even) if __name__ == '__main__': sol = Solution() # tree = TreeNode.from_list([3, 2, 3, None, 3, None, 1]) tree = TreeNode.from_list([4, 1, None, 2, None, 3]) print(tree) print(sol.rob(tree))
def mirrorTree(self, root: TreeNode) -> Optional[TreeNode]: if not root: return root.left, root.right = self.mirrorTree(root.right), self.mirrorTree( root.left) return root
from base.tree.tree_node import TreeNode from typing import Optional class Solution: def mirrorTree(self, root: TreeNode) -> Optional[TreeNode]: if not root: return root.left, root.right = self.mirrorTree(root.right), self.mirrorTree( root.left) return root if __name__ == '__main__': tree = TreeNode.from_list([4, 2, 7, 1, 3, 6, 9]) sol = Solution() a = sol.mirrorTree(tree) print(a)
# todo # 错误的,想仿照排列数和组合数进行回溯,因为是树型结构,但是没成功 class Solution: def pathSum(self, root: TreeNode, total: int) -> List[List[int]]: res = [] def dfs(root: TreeNode, total: int, one_ans): if sum(one_ans) == total: res.append(one_ans) if root.left: one_ans.append(root.val) dfs(root.left, total, one_ans) one_ans.pop() if root.right: one_ans.append(root.val) dfs(root.right, total, one_ans) one_ans.pop() one_ans = [] dfs(root, total, one_ans) return res if __name__ == '__main__': tree = TreeNode.from_list( [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, None, 5, 1]) print(tree) sol = Solution() print(sol.pathSum(tree, 22))
from base.tree.tree_node import TreeNode class Solution: def minDiffInBST(self, root: TreeNode) -> int: res = [] def inorder(root: TreeNode): if root: inorder(root.left) if root.val is not None: res.append(root.val) inorder(root.right) inorder(root) min_val = float("inf") for i in range(1, len(res)): val = res[i] - res[i - 1] if val < min_val: min_val = val return min_val if __name__ == '__main__': sol = Solution() tree = TreeNode.bst_from_list([4, 2, 6, 1, 3]) a = sol.minDiffInBST(tree) print(a)
from base.tree.tree_node import TreeNode class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: a = [] def inorder(root, a): if len(a) == k: return if root: inorder(root.left, a) a.append(root.val) inorder(root.right, a) inorder(root, a) return a[k - 1] if __name__ == '__main__': treeNode = TreeNode(3) treeNode.left = TreeNode(1) treeNode.right = TreeNode(4) treeNode.left.right = TreeNode(2) sol = Solution() print(sol.kthSmallest(treeNode, 1))
# Tree problem -> travserd -> two parts -> the second part need some element # 1. None -> True # 2. False # 3. travserd the until True or Flase # ptr is ALL if root is None: return True if root.val <= largerThan or root.val >= lessThan: return False return self.isValidBSTRec(root.left, min( lessThan, root.val), largerThan) and self.isValidBSTRec( root.right, lessThan, max(root.val, largerThan)) if __name__ == '__main__': tree1 = TreeNode(2) tree1.left = TreeNode(1) tree1.right = TreeNode(3) sol = Solution() assert sol.isValidBST(tree1) == True tree2 = TreeNode(5) tree2.left = TreeNode(1) tree2.right = TreeNode(4) tree2.right.left = TreeNode(3) tree2.right.right = TreeNode(6) assert sol.isValidBST(tree2) == False tree3 = TreeNode(1) tree3.left = TreeNode(1) assert sol.isValidBST(tree3) == False
return True res, queue = [], [root] a = 1 while queue: next_level, curr_vals = [], [] for i in queue: if i and i.val is not None: curr_vals.append(i.val) if i.left: next_level.append(i.left) if i.right: next_level.append(i.right) queue = next_level if a % 2 == 1: if is_odd(curr_vals) is False: return False else: if is_even(curr_vals) is False: return False a += 1 return True if __name__ == '__main__': tree = TreeNode.from_list([1, 10, 4, 3, None, 7, 9, 12, 8, 6, None, None, 2]) sol = Solution() t = sol.isEvenOddTree(tree) print(t)
from collections import deque from base.tree.tree_node import TreeNode class Solution: def levelOrder(self, root: TreeNode): if root is None: return [] result, queue = [], [root] while queue: next_level, curr_vals = [], [] for node in queue: if node.val is not None: curr_vals.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) queue = next_level result.append(curr_vals) return result if __name__ == '__main__': tree = TreeNode.from_list([3, 9, 20, None, None, 15, 7]) print(tree) sol = Solution() t = sol.levelOrder(tree) print(t)
def preorderNonRecursive(self, root): if root is None: return [] stack, res = [root], [] while stack: node = stack.pop() res.append(node.val) if node.right is not None: stack.append(node.right) if node.left is not None: stack.append(node.left) return res if __name__ == '__main__': tree = TreeNode(6) tree.left = TreeNode(8) tree.right = TreeNode(4) tree.left.left = TreeNode(9) tree.left.right = TreeNode(7) tree.right.left = TreeNode(5) tree.right.right = TreeNode(3) print(bfs(tree)) print("---------") # print(dfs(tree)) print('---------') print(f'inorder is {inorderTraversal(tree)}') print(f'dfs preorder is {dfsPreorder(tree)}') print(f'dfs postorder is {dfsPostorder(tree)}') # print(f'inorderTravsalTest is {inorderTraversalTest(tree)}')