1. 程式人生 > >Input is a BST(python+cpp)

Input is a BST(python+cpp)

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

解釋: 輸入是一顆二叉樹,第一反應是先遍歷一遍二叉樹把樹的結點的值存成list,然後用Two Sum II的解法做(因為BST中序遍歷以後是有序的),後來反應過來可以直接在遍歷的過程中存dict,無需先存成有序list,這裡其實是被BST的中序有序性質迷惑了。 剛開始的想法,python程式碼,速度極慢:

# 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 middle(self,root,a): if root==None: return None self.middle(root.left,a) a.append(root.val) self.middle(root.right,a) return a def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """
b=[] a=self.middle(root,b) print a i=0 j=len(a)-1 while i<j: if a[i]+a[j]<k: i+=1 elif a[i]+a[j]>k: j-=1 else: return True return False

實際上前序遍歷一遍即可。

# 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 findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        _set=set()
        def dfs(root):
            if not root:
                return False
            if k-root.val in _set:
                return True
            _set.add(root.val)
            return dfs(root.left) or dfs(root.right)
        return dfs(root) 

c++程式碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<set>
using namespace std;
class Solution {
public:
    set<int> _set;
    bool findTarget(TreeNode* root, int k) {
        return dfs(root,k)  
    }
    bool dfs(TreeNode *root ,int k)
    {
        if (! root)
            return false;
        if(count(_set.begin(),_set.end(),k-root->val))
            return true;
        _set.insert(root->val);
        return dfs(root->left,k)||dfs(root->right,k);
    }
};

總結: 對於二叉樹的問題,有時候或許可以直接在遍歷的時候處理一些事情,不一定非要遍歷完了再處理。