zoukankan      html  css  js  c++  java
  • [LeetCode] Two Sum IV

    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
  • 相关阅读:
    goj 天涯若比邻(最小与最大相邻素数)
    HTML5_CSS3可切换注册登录表单
    粒子效果进度条
    鼠标滑过抖动图标
    HTML5/CSS3鼠标滑过图片滤镜动画效果
    自定义抖动表单
    3D焦点图插件
    CSS3自定义Checkbox特效
    CSS3自定义下拉框菜单
    Flash+XML前后按钮超酷焦点图
  • 原文地址:https://www.cnblogs.com/immjc/p/7500427.html
Copyright © 2011-2022 走看看