题解 | #二叉搜索树的后序遍历序列#
二叉树中和为某一值的路径(一)
http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(!root)return false;
int sum1=0;
return pathSum(root,sum,sum1);
}
bool pathSum(TreeNode* root, int sum,int sum1){
if(!root)return false;
sum1+=root->val;//局部变量
cout<<sum1<<endl;//累加和
if(sum1==sum&&root->left==NULL&&root->right==NULL)return true;
//找它的左右子树
return pathSum(root->left, sum, sum1)||
pathSum(root->right, sum,sum1);
}
};
查看12道真题和解析