码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Two Sum IV - Input is a BST

时间:2017-09-10 12:24:54      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:point   number   get   bst   target   poi   public   struct   col   

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

标签:point   number   get   bst   target   poi   public   struct   col   

原文地址:http://www.cnblogs.com/immjc/p/7500427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!