标签:des style blog http color os
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: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.
递归实现
从树根开始判断
class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL && sum == root->val) return true; else return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right, sum-root->val); } };
class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL) return sum == root->val; sum-=root->val; return hasPathSum(root->left,sum) || hasPathSum(root->right, sum); } };
非递归遍历(根据层次遍历实现即可)
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <iostream> #include <queue> using namespace std; struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x), left(NULL),right(NULL){} }; struct TreeNodeSum{ TreeNode *node; int sum; TreeNodeSum(TreeNode* node_, int sum_ ):node(node_),sum(sum_){} }; bool hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; queue<TreeNodeSum *> que; que.push(new TreeNodeSum(root,root->val)); int res = 0; while(!que.empty()){ TreeNodeSum *tmp = que.front();que.pop(); TreeNode *node = tmp->node; cout<<node->val<<endl; if(!node->left && !node->right && tmp->sum == sum) return true; if(node->left){ TreeNodeSum *nodeSum = new TreeNodeSum(node->left,node->left->val+tmp->sum); que.push(nodeSum); } if(node->right ){ TreeNodeSum *nodeSum = new TreeNodeSum(node->right,node->right->val+tmp->sum); que.push(nodeSum); } } return false; } int main(){ TreeNode *root = new TreeNode(1); TreeNode *root1 = new TreeNode(-2); TreeNode *root2 = new TreeNode(-3); TreeNode *root3 = new TreeNode(1); TreeNode *root4 = new TreeNode(3); TreeNode *root5 = new TreeNode(-2); TreeNode *root6 = new TreeNode(-1); root->left = root1; root->right = root2; root1->left = root3; root1->right = root4; root2->left = root5; root3->left = root6; cout<<hasPathSum(root,-1)<<endl; }
Leetcode Path Sum,布布扣,bubuko.com
标签:des style blog http color os
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3818959.html