LeetCode 653. Two Sum IV - Input is a BST(在BST中寻找两个节点,使它们的和为一个给定值)
Posted SomnusMistletoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 653. Two Sum IV - Input is a BST(在BST中寻找两个节点,使它们的和为一个给定值)相关的知识,希望对你有一定的参考价值。
题意:在BST中寻找两个节点,使它们的和为一个给定值。
/** * 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> v; void inorder(TreeNode* root){ if(root == NULL) return; inorder(root -> left); v.push_back(root -> val); inorder(root -> right); } bool findTarget(TreeNode* root, int k) { if(root == NULL) return false; inorder(root); int len = v.size(); int head = 0; int tail = len - 1; while(head < tail){ int sum = v[head] + v[tail]; if(sum == k) return true; else if(sum > k) --tail; else ++head; } return false; } };
以上是关于LeetCode 653. Two Sum IV - Input is a BST(在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
653. Two Sum IV - Input is a BST
LeetCode 653. Two Sum IV - Input is a BST(在BST中寻找两个节点,使它们的和为一个给定值)