* 这题属于Two Sum题,将BST中根遍历存到数组当中,转换为数组的Two Sum问题即可 *
C # 代码
public bool FindTarget(TreeNode root, int k)
{
List<int> lst = new List<int>();
BST2Lst(root,ref lst);
int i = 0;
int j = lst.Count-1;
while(i<j)
{
if(lst[i] + lst[j] == k)
{
return true;
}
if( lst[i]+lst[j] < k)
i++;
else
j--;
}
return false;
}
public void BST2Lst(TreeNode root, ref List<int> lst)
{
if(root == null)
return ;
BST2Lst(root.left, ref lst);
lst.Add(root.val);
BST2Lst(root.right, ref lst);
}
python 3代码
class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
lst = []
self.BST2Lst(root, lst)
i = 0
j = len(lst)-1
while(i<j):
flag = lst[i]+lst[j]
if flag == k :
return True
if flag < k:
i += 1
else:
j -= 1
return False
def BST2Lst(self, root, lst):
if root == None:
return
self.BST2Lst(root.left, lst)
lst.append(root.val)
self.BST2Lst(root.right, lst)