码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode112——Path Sum

时间:2015-01-13 19:55:05      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:二叉树   path   c++   leetcode   

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.

题目大意:给定一个二叉树和一个值sum,判断是否存在一个从根节点到叶子节点的路径,使得路径上每个节点值之和等于sum?

难度系数:容易 (共3级别:容易,中等,困难)

看到这个题目,大体思路就是遍历从根到叶子的每一条路径,并求和。只要相等,就返回true,否则一直遍历下去,最后返回false。

这一次,我没有编译,测试,全在脑子里演算。共3次提交通过,一次是特殊情况没考虑到,一次是被上面的例子误导了,以为sum是正数。 第三次提交通过了。代码如下:

bool hasPathSum(TreeNode *root, int sum) {
    if (root == NULL)
        return false;
    else if (root->left == NULL && root->right == NULL && root->val == sum)
        return true;
    else {
        return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum - root->val);
    }
}

10行不到。做完后我搜索了下,看看别人是怎么做的,发现好多人写了30行左右的代码,看到这样的代码,我也无力吐槽了。我觉得 精简可读还是很重要的,毕竟是写给人看的。Martin Fowler有句名言:

任何傻瓜都能写出计算机可以理解的代码。好的程序员能写出人能读懂的代码

一般来说,写的复杂,冗长的代码,往往是用的解法不够好。而且实际项目中,往往时间紧迫,确实让人很难做到写出可读性好的代码来。

很久没有去游玩了。希望有一天,能摆脱金钱的烦恼,边写代码,边赏风景。 登临险峰观赏无限的风光,骑行西藏感悟人生的真谛;闲看路上匆匆的行人,静听山涧叽叽的鸟声。。。

LeetCode112——Path Sum

标签:二叉树   path   c++   leetcode   

原文地址:http://blog.csdn.net/booirror/article/details/42680111

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!