import sys sys.path.append('com/DataStructure/Python') from BinarySearchTree import BinarySearchTree class Solution: def isValidTree(self, root, minN, maxN): if root is None: return True if root.val > minN and root.val < maxN: return self.isValidTree(root.left, minN, root.val) and self.isValidTree( root.right, root.val, maxN) else: return False def isValidBST(self, root): return self.isValidTree(root, float('-inf'), float('inf')) test = BinarySearchTree() test.addNode(6) test.addNode(4) test.addNode(8) test.printTree(test.getRoot()) sol = Solution() print(sol.isValidBST(test.getRoot()))
def invertTreeDfs(self, root): stack = [root] while stack: current = stack.pop() if current: current.left, current.right = current.right, current.left stack.append(current.left) stack.append(current.right) return root def invertTreeRecursion(self, root): if not root: return root.left, root.right = root.right, root.left self.invertTreeRecursion(root.left) self.invertTreeRecursion(root.right) return root test = BinarySearchTree() test.addNode(4) test.addNode(2) test.addNode(7) test.addNode(1) test.addNode(3) test.addNode(6) test.addNode(9) test.printTreeBfs(test.getRoot()) sol = Solution() test.printTreeBfs(sol.invertTreeRecursion(test.getRoot()))