Exemple #1
0
 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
        # 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
Exemple #3
0
# 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)}')
 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


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))