两数之和 - BST版本-LintCode

给一棵二叉搜索树以及一个整数 n, 在树中找到和为 n 的两个数字

注意事项:
Without any extra space.

样例:
给一棵BST:

    4
   / \
  2   5
 / \
1   3

以及一个整数 n = 3
返回 [1, 2] 或 [2, 1]

思路:
遍历节点,求得节点值与n的差,从根开始寻找值为差的节点是否存在。

#ifndef C689_H
#define C689_H
#include<iostream>
#include<vector>
using namespace std;
class TreeNode{
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val)
    {
        this->val = val;
        this->left = this->right = NULL;
    }
};
class Solution {
public:
    /*
    * @param : the root of tree
    * @param : the target sum
    * @return: two number from tree witch sum is n
    */
    vector<int> twoSum(TreeNode * root, int n) {
        // write your code here
        vector<int> res;
        if (root == NULL)
            return res;
        TreeNode *p = root;
        createVec(root, p, n, res);
        return res;
    }
    //p为root中的任意一个节点,找到满足条件的节点则返回,否则继续遍历
    void createVec(TreeNode *root, TreeNode *p, int n,vector<int> &res)
    {
        if (p == NULL)
            return;
        if (isValid(root, n - p->val))
        {
            res.push_back(p->val);
            res.push_back(n - p->val);
            return;
        }
        else
        {
            createVec(root, p->left, n, res);
            createVec(root, p->right, n, res);
        }
    }
    //判断以root为根的树中,是否存在值为n的节点
    bool isValid(TreeNode *root, int n)
    {
        if (root == NULL)
            return false;
        if (n > root->val)
        {
            if (root->right == NULL)
                return false;
            else
                return isValid(root->right, n);
        }
        else if (n == root->val)
            return true;
        else
        {
            if (root->left == NULL)
                return false;
            else
                return isValid(root->left, n);
        }
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值