LeetCode Path Sum

来源:互联网 发布:微信牛牛机器人软件 编辑:程序博客网 时间:2024/05/20 15:41

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.


/* * bts.cpp * *  Created on: 2015年4月14日 *      Author: judyge */#include <stdio.h>#include <iostream>#include <stack>#include <map>using namespace std; struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {} };// 因为是判断目的是否可达   深度优先搜索好  用递归bool dfs(TreeNode *node, int sum, int curSum){if (node == NULL)            return false;   //空树if (node->left == NULL && node->right == NULL)            return curSum + node->val == sum;  //只有根节点的树return dfs(node->left, sum, curSum + node->val) || dfs(node->right, sum, curSum + node->val);//递归遍历左右两棵树数}bool hasPathSum(TreeNode *root, int sum) {        return dfs(root, sum, 0);}


0 0
原创粉丝点击