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.
For 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.
题目大意:判断是否存在一条路径,且其上的和与给定的sum相等。
1.我的解法(递归)
/** * 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: bool pathsum(TreeNode* root, int all, int sum){ if(root->left== NULL && root->right == NULL){ if(all+root->val == sum) return true; else return false; } if(root->left== NULL || root->right == NULL){//这里需要处理只有一个子节点的情况,不能把有空的那条算为路径 TreeNode* t = root->left!=NULL?root->left:root->right; return pathsum(t,all+root->val,sum); }else{ return pathsum(root->left,all+root->val,sum)||pathsum(root->right,all+root->val,sum); } } bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; return pathsum(root,0,sum); } };
对上面做改进。这里主要就是针对某个节点只有一个左/右节点该怎么处理。
上面做法是,如果碰到只有一个子节点,则将那个子节点传下去;
下面的做法是,如果碰到空了(只有一个子节点,则另一个子节点就是为空,),那么这个分叉不属于一条路径,则直接置false。
因为只有到叶子节点(左右都为空),才算一条路径。
/** * 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: bool pathsum(TreeNode* root, int all, int sum){ if(root==NULL) return false; if(root->left== NULL && root->right == NULL){ if(all+root->val == sum) return true; else return false; } return pathsum(root->left,all+root->val,sum)||pathsum(root->right,all+root->val,sum); } bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; return pathsum(root,0,sum); } };
2.别人的解法(递归)
bool hasPathSum(TreeNode *root, int sum) { if (root == NULL) return false; if (root->val == sum && root->left == NULL && root->right == NULL) return true; return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val); }
时间: 2024-10-09 10:50:47