https://oj.leetcode.com/problems/path-sum/
树的深搜,求从根到叶子的路径。
记住深搜的样子
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool hasPathSum(TreeNode *root, int sum) { //null if(root == NULL ) return false; //leaf node if(root->left == NULL && root->right == NULL && root->val == sum) return true; if(root->left == NULL && root->right == NULL) return false; //not leaf node if(root->left ||root->right) { bool ans = false; if(root->left) { ans = hasPathSum(root->left, sum - root->val); if(ans == true) return true; } if(root->right) { ans = hasPathSum(root->right, sum-root->val); if(ans == true) return true; } return false; } return false; } }; int main() { TreeNode *n1 = new TreeNode(1); TreeNode *n2 = new TreeNode(-2); TreeNode *n3 = new TreeNode(-3); TreeNode *n4 = new TreeNode(1); TreeNode *n5 = new TreeNode(3); TreeNode *n6 = new TreeNode(-2); TreeNode *n7 = new TreeNode(-1); n1->left = n2; n1->right = n3; n2->left = n4; n2->right = n5; n3->left = n6; n3->right = NULL; n4->left = n7; class Solution myS; cout<<myS.hasPathSum(n1,2); return 0; }