博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Path Sum
阅读量:4649 次
发布时间:2019-06-09

本文共 1119 字,大约阅读时间需要 3 分钟。

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.

思考:深度优先遍历。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void DFS(TreeNode *root,int sum,int ans,bool &flag)    {        if(root)        {            ans+=root->val;            if(ans==sum&&!root->left&&!root->right)            {                flag=true;            }            DFS(root->left,sum,ans,flag);            DFS(root->right,sum,ans,flag);        }    }    bool hasPathSum(TreeNode *root, int sum) {        int ans=0;        bool flag=false;        DFS(root,sum,ans,flag);        return flag;    }};

  

转载于:https://www.cnblogs.com/Rosanna/p/3458444.html

你可能感兴趣的文章
[Leetcode] unique paths ii 独特路径
查看>>
HDU 1217 Arbitrage (Floyd + SPFA判环)
查看>>
IntelliJ idea学习资源
查看>>
Django Rest Framework -解析器
查看>>
ExtJs 分组表格控件----监听
查看>>
Hibernate二级缓存配置
查看>>
LoadRunner常用术语
查看>>
关于jedis2.4以上版本的连接池配置,及工具类
查看>>
记忆讲师石伟华微信公众号2017所有文章汇总(待更新)
查看>>
mechanize (1)
查看>>
FactoryBean
查看>>
Coolite动态加载CheckboxGroup,无法在后台中获取
查看>>
如何在我们项目中利用开源的图表(js chart)
查看>>
nfs服务器工作原理
查看>>
C3P0连接池工具类使用
查看>>
SVN常用命令备注
查看>>
孩子教育
查看>>
解决Cacti监控图像断断续续问题
查看>>
结构体的传参理解成员的存储方式
查看>>
python 进程与线程(理论部分)
查看>>