Esempio n. 1
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. 2
0
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

"""


class Solution:
    """Solution class"""
    def maxDepth(self, root: TreeNode) -> int:
        """Gets the maximum depth of a binary tree
        Args:
            root: root of the binary tree
        Return: integer, depth of root
        """
        if not root:
            return 0
        return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)


# main
tree = toBinaryTree([3, 9, 20, None, None, 15, 7])
sol = Solution()
print(sol.maxDepth(tree))
Esempio n. 3
0
        Args:
            root: root node type TreeNode
            p: TreeNode to search
            q: TreeNode to search
        Return:
            A TreeNode representing the LCA of q and p
        """
        if not root:
            return None
        if root.val == p.val or root.val == q.val:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        elif left and not right:
            return left
        elif right and not left:
            return right


# main
sol = Solution()
tree = toBinaryTree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
printTree(tree)
print("==================")
print(sol.lowestCommonAncestor(tree, TreeNode(5), TreeNode(1)).val)
printTree(tree)
print("==================")
print(sol.lowestCommonAncestor(tree, TreeNode(5), TreeNode(4)).val)
Esempio n. 4
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. 5
0
        [1,2,3],   [1,2,3]

Output: true

"""


class Solution:
    """Solution"""
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        """Checks if two binary trees are the same
        Args:
            p: TreeNode tree
            q: TreeNode tree
        Return:
            True or False
        """
        if not p and not q:
            return True
        if not p or not q or p.val != q.val:
            return False
        return (self.isSameTree(p.left, q.left)
                and self.isSameTree(p.right, q.right))


# main
tree1 = toBinaryTree([1, 2, 3])
tree2 = toBinaryTree([1, 2, 3])
sol = Solution()
print(sol.isSameTree(tree1, tree2))
Esempio n. 6
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))
Esempio n. 7
0
    """
    Solution to validate binary tree problem
    """
    def isValidBST(self, root: TreeNode) -> bool:
        """
        Args:
            root: root node of the binary tree
        Return: True or False
        """
        stack = []
        prev = float('-inf')
        if not root:
            return True
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if root.val <= prev:
                return False
            prev = root.val
            root = root.right
        return True


# main
tree = toBinaryTree([2, 1, 3])
printTree(tree)
sol = Solution()
print(sol.isValidBST(tree))
Esempio n. 8
0
            level = []
            i = 0
            queueLen = len(queue)
            # queueLen represents the number of nodes in each level
            while i < queueLen:
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                level.append(node.val)
                i += 1
            if levIdx % 2 == 0:
                zigzag.append(level)
            else:
                zigzag.append(level[::-1])
            levIdx += 1
        return zigzag


# main
tree = toBinaryTree([3, 9, 20, None, None, 15, 7])
printTree(tree)
sol = Solution()
print(sol.zigzagLevelOrder(tree))
print("==================")
tree = toBinaryTree([3, 9, 20, 29, 45, 15, 7])
printTree(tree)
sol = Solution()
print(sol.zigzagLevelOrder(tree))