[LeetCode] Two Sum IV - Input is a BST

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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

给定一个二叉树,对其求树中两个元素的和是否满足给定值。

1. 对二叉树进行中序遍历并把结果放入一个数组中

2. 对数组进行Two Pointer查找即可。

/**
 * 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:
    vector<int> inOrder;
    bool findTarget(TreeNode* root, int k) {
        if (root == nullptr)
            return false;
        inOrdertoVec(root);
        if (inOrder.size() == 1)
            return false;
        int left = 0, right = inOrder.size() - 1;
        while (left < right) {
            int sum = inOrder[left] + inOrder[right];
            if (sum == k)
                return true;
            else if (sum < k)
                left++;
            else
                right--;
        }
        return false;
        
    }
    vector<int> inOrdertoVec(TreeNode* root) {
        if (root == nullptr)
            return inOrder;
        stack<TreeNode*> s;
        while (root || !s.empty()) {
            if (root != nullptr) {
                s.push(root);
                root = root->left;
            } 
            else {
                root = s.top();
                inOrder.push_back(root->val);
                s.pop();
                root = root->right;
            }
        }
        return inOrder;
    }
};
// 35 ms

 

以上是关于[LeetCode] Two Sum IV - Input is a BST的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 653. Two Sum IV - Input is a BST

LeetCode 653. Two Sum IV - Input is a BST

leetcode 653. Two Sum IV - Input is a BST

[Leetcode] Binary tree--653. Two Sum IV - Input is a BST

[Leetcode]653.Two Sum IV - Input is a BST

[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树