zoukankan      html  css  js  c++  java
  • Leetcode653.Two Sum IV

    给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。

    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    
    class Solution {
    public:
        TreeNode* node;
        bool findTarget(TreeNode* root, int k) {
            if(root == NULL)
                return false;
            node = root;
            return GetAns(root, k);
        }
    
        bool GetAns(TreeNode* root, int k)
        {
            if(root == NULL)
                return false;
            int temp = k - root ->val;
            TreeNode* t = Search(node, temp);
            if(t != NULL && t != root)
                return true;
            return GetAns(root ->left, k) || GetAns(root ->right, k);
        }
    
        TreeNode* Search(TreeNode* root, int k)
        {
            if(root == NULL)
                return NULL;
            if(root ->val == k)
                return root;
            else if(root ->val > k)
                return Search(root ->left, k);
            else return Search(root ->right, k);
        }
    };
    
  • 相关阅读:
    111
    实验 12 综合练习二
    实验 11结构体
    作业 5 指针应用1
    实验 10 指针2
    实验9 指针1
    实验8 数组2
    实验7
    321
    实验9-2
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10434027.html
Copyright © 2011-2022 走看看