Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5 / 4 8 / / 11 13 4 / 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
方法一:利用深度优先搜索DFS的方法来遍历每一条完整的路径,利用递归方法不停地找子节点的左右结点。首先,若输入的是空节点,则返回false,若是为叶子结点且其值为当下的值时,则返回true,否则,只要子节点的左右结点中任一结点可行则返回true。(C++)
1 bool hasPathSum(TreeNode* root, int sum) { 2 if(!root) 3 return false; 4 if(root->val==sum&&!root->left&&!root->right) 5 return true; 6 return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val); 7 }
方法二:使用遍历的方法,每一个结点都加上其父结点的值,如果到叶子结点时,其值等于sum,就存在一条符合题意的路径,在这道题中,不一定非要右结点先入栈,左右顺序不影响结果。(C++)
1 bool hasPathSum(TreeNode* root, int sum) { 2 if(!root) 3 return false; 4 stack<TreeNode*> s{{root}}; 5 while(!s.empty()){ 6 TreeNode* tmp=s.top(); 7 s.pop(); 8 if(!tmp->left&&!tmp->right){ 9 if(tmp->val==sum) 10 return true; 11 } 12 if(tmp->right){ 13 tmp->right->val+=tmp->val; 14 s.push(tmp->right); 15 } 16 if(tmp->left){ 17 tmp->left->val+=tmp->val; 18 s.push(tmp->left); 19 } 20 } 21 return false; 22 }