653. Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True
Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False

Solution

class Solution:
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        if not root:
            return False
        stack = [root]
        s = set()
        while stack:
            node = stack.pop()
            if node.val in s:
                return True
            s.add(k-node.val)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return False

606. Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())", 
but you need to omit all the unnecessary empty parenthesis pairs. 
And it will be "1(2(4))(3)".
Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \  
      4 

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example, 
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

Solution

class Solution:
    def tree2str(self, t):
        """
        :type t: TreeNode
        :rtype: str
        """
        if not t:
            return ''
        if not t.left and t.right:
            return str(t.val) + '()' + '(' + str(self.tree2str(t.right)) + ')'
        elif t.left and not t.right:
            return str(t.val) + '(' + str(self.tree2str(t.left)) + ')'
        elif not t.left and not t.right:
            return str(t.val)
        else:
            return str(t.val) + '(' + str(self.tree2str(t.left)) + ')' + '(' + str(self.tree2str(t.right)) + ')'

TurtleLin
1 声望0 粉丝

黄渡理工大学就读