美文网首页
653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

作者: 安东可 | 来源:发表于2018-03-28 22:05 被阅读6次

653. Two Sum IV - Input is a BST
【思路】:

  1. 一般采用深度遍历;
  2. 和= 顶点+ 右子树 || 左子树+ 右子树 || 左子树+顶点;
  3. 使用中序遍历获得顺序,然后通过前后相加比较;
  4. Leetcode 653. Two Sum IV - Input is a BST
    bool findTarget(TreeNode* root, int k) {
        vector<int> res;
        dfs_inorder(root,res);
        int sum=0;
        int len = res.size();
        int i=0;
        int j = len-1;
        cout<<"size: "<<len<<endl;
        while(i<len){
            sum = res[i] + res[j];
            if(sum > k)
                j --;
            else if(sum < k)
                i++;
            else
                return true;
        }
        return false;
        
        
    }
    
// DFS
    void dfs_inorder(TreeNode* root, vector<int>& res){
        if(! root )return;
        //cout<<"val: "<<root->val<<endl;
        dfs_inorder(root->left,res);
        res.push_back(root->val);
        dfs_inorder(root->right,res);
    }




相关文章

网友评论

      本文标题:653. Two Sum IV - Input is a BST

      本文链接:https://www.haomeiwen.com/subject/mnrecftx.html