leetcode 112 Path Sum 路径和

437 path sum

 C++:使用递归先序遍历,记录根节点到当前节点的路径和,如果当前节点是叶节点,判断是否等于sum

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool hasPathSum(TreeNode* root, int sum) {
13         bool res=false;
14         dfs(root,sum,0,res);
15         return res;
16     }
17     void dfs(TreeNode* node,int sum,int curSum,bool &res){
18         if(!node) return;
19         curSum+=node->val;
20         if(node->left==NULL&&node->right==NULL&&curSum==sum) res=true;
21         dfs(node->left,sum,curSum,res);
22         dfs(node->right,sum,curSum,res);
23     }
24 };

 

posted @ 2019-02-28 22:20  Joel_Wang  阅读(118)  评论(0编辑  收藏  举报