Esempio n. 1
0
    def invertTree(self, root: TreeNode) -> TreeNode:
        """Inverts a binary tree
        Args:
            root: root node of the tree
        Return:
            root node of the inverted tree
        """
        queue = Queue(root)
        if not root:
            return None

        while queue:
            node = queue.node
            temp = node.left
            node.left = node.right
            node.right = temp
            if node.left:
                queue.addToQueue(node.left)
            if node.right:
                queue.addToQueue(node.right)
            queue = queue.popQueue()
        return root


# main
tree = toBinaryTree([4, 2, 7, 1, 3, 6, 9])
printTree(tree)
print("==================")
sol = Solution()
printTree(sol.invertTree(tree))
Esempio n. 2
0
    def kthSmallestRecursive(self, root: TreeNode, k: int) -> int:
        self.k = k
        return self.findKthInorder(root)

    def kthSmallestIterative(self, root: TreeNode, k: int) -> int:
        """Finds the kth smallest element in a binary tree
        Args:
            root: TreeNode binary tree
            k: integer representing the smallest number in root
        Returns:
            The kth TreeNode value
        """
        stack = []
        while root or stack:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            k -= 1
            if k == 0:
                return root.val
            root = root.right


# main
tree = toBinaryTree([3, 1, 4, None, 2])
printTree(tree)
sol = Solution()
smallest = sol.kthSmallestIterative(tree, 1)
print(smallest)
Esempio n. 3
0
            return False
        if s.val != t.val:
            return False
        return (self.checkAll(s.left, t.left)
                and self.checkAll(s.right, t.right))

    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
        """
        Check if a tree is a subtree of another tree
        Args:
            s: binary tree
            t: binary tree (subtree)
        Return:
            True or False
        """
        if not s or not t:
            return False

        if self.checkAll(s, t):
            return True
        return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)


# main
tree1 = toBinaryTree([3, 4, 5, 1, 2])
tree2 = toBinaryTree([4, 1, 2])
printTree(tree1)
printTree(tree2)
sol = Solution()
print(sol.isSubtree(tree1, tree2))