653. Two Sum IV - Input is a BST

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 res;
        dfs_inorder(root,res);
        int sum=0;
        int len = res.size();
        int i=0;
        int j = len-1;
        cout<<"size: "< k)
                j --;
            else if(sum < k)
                i++;
            else
                return true;
        }
        return false;
        
        
    }
    
// DFS
    void dfs_inorder(TreeNode* root, vector& res){
        if(! root )return;
        //cout<<"val: "<val<left,res);
        res.push_back(root->val);
        dfs_inorder(root->right,res);
    }




你可能感兴趣的:(653. Two Sum IV - Input is a BST)