leetcode653. Two Sum IV - Input is a BST

xiaoxiao2021-02-28  133

题意是求二叉树中的任意两个数的和能不能是k。

把二叉树便利一遍,求出所有元素,然后在循环便利每两个的和就好。

/** * 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> s; void f(TreeNode* root){ if(root!=NULL) s.push_back(root->val); if(root->left!=NULL) f(root->left); if(root->right!=NULL) f(root->right); } bool findTarget(TreeNode* root, int k) { f(root); int n=s.size(); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(s[i]+s[j]==k) return 1; } } return 0; } };

转载请注明原文地址: https://www.6miu.com/read-18101.html

最新回复(0)