leetcode 关于树的题目

判断一棵树里是否有两个节点的值之和等于某个值。

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

 

Example 2:

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

Target = 28

Output: False
思路:使用 unordered_set存储🌲节点的值。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    unordered_set<int> s;
    bool dfs(TreeNode* root,int k, unordered_set<int>& s){
        if(root==nullptr) return false;
        if(s.count(k-root->val)) return true;
        s.insert(root->val);
        return dfs(root->left,k,s)||dfs(root->right,k,s);
    }
public:
    bool findTarget(TreeNode* root, int k) {
        s.clear();
        return dfs(root,k,s);
    }
};

 python代码

创建集合 set(), 插入 add (c++ insert)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def helper(self,root,k,s):
        if not root:
            return False
        if k-root.val in s:
            return True
        s.add(root.val)
        return self.helper(root.left,k,s) or self.helper(root.right,k,s)
    
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        s=set()
        return self.helper(root,k,s)
        
        

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

 

Example 2:

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.

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    string tree2str(TreeNode* t) {
        if(t==nullptr)
            return "";
        string s=to_string(t->val);
        if(t->left==nullptr){
            if(t->right==nullptr)
                return s;
            else{
                return s+"()"+"("+tree2str(t->right)+")";
            }
        }else{
            return s+"("+tree2str(t->left)+")"+(!t->right?"":"("+tree2str(t->right)+")");
        }
    }
};
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

 

posted @ 2018-07-08 17:13  hopskin1  阅读(107)  评论(0编辑  收藏  举报