AC solution with O(logn) space and O(n*logn) time for balanced BST

  • 0

    Since in a balanced tree it takes O(logn) to find a number, we can traverse the tree and for every number in it check if its complement exists. Total time is O(n*logn). No extra space needed except for the stack, which is O(logn).

    class Solution(object):
        def findNumInBST(self, root, num):
            if root:
                if root.val < num:
                    return self.findNumInBST(root.right, num)
                if root.val > num:
                    return self.findNumInBST(root.left, num)
                return True
            return False
        def findTarget(self, root, k):
            :type root: TreeNode
            :type k: int
            :rtype: bool
            stack = [root]
            while stack:
                node = stack.pop()
                if node.val + node.val != k and self.findNumInBST(root, k - node.val):
                    return True
                for node in (node.left, node.right):
                    if node:
            return False

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.