LeetCode Path Sum
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.
从Root结点->遍历到叶子结点 找出sum跟遍历的总和相同 返回真 or 假
Leetcode
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ bool hasPathSum(TreeNode *root, int sum) { return PathSum(root,sum,0); } bool PathSum(TreeNode *root,int sum,int val) { if(root==NULL) return false;//如果给出的节点为空则返回假 val+=root->val;//不为空 则将当前递归 节点的val 值进行+=操作 if(root-left== NULL&&root->right==NULL)//递归到叶子结点 { if(sum==val) return true; else false; } return PathSum(root->left,sum,val)||PathSum(root->right,sum,val);//如果当前递归到非叶子结点 则继续递归调用 结点的 左 右 两个孩子结点 }
广度 深度 搜索 的变化 还是多样的 要多多了解这些思想 跟方法
posted on 2015-07-19 18:37 winters1992x 阅读(87) 评论(0) 编辑 收藏 举报