112 Path Sum


title: Path Sum
tags:
- path-sum
- No.112
- simple
- tree
- recursive


Description

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.

Note: A leaf is a node with no children.

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.

Corner Cases

  • empty tree

Solutions

Recursively reduce the value of the current node from sum. The running time is the same as BFS, O(V):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {return false;}        
        return f(root, sum);
    }
    
    private boolean f(TreeNode x, int s) {
        if (x.left == null && x.right == null && x.val == s) {return true;}
        
        boolean fl = false;
        boolean fr = false;
        if (x.left  != null) {fl = f(x.left,  s - x.val);}
        if (x.right != null) {fr = f(x.right, s - x.val);}        
        return fl || fr;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 朋友雯长相清秀,性格落落大方、有想法,在工作上坚持5年获得部门经理职位,事业顺风顺水的她,感情却异常晚熟 ,一不着...
    无法抗拒的温暖阅读 326评论 0 0
  • 30天产品强化训练之观察篇 三相同 1、都做了社区。 2、都是针对健身人群; 3、 社区用户日志详情页基本架构相同...
    Hans长夜下阅读 536评论 0 1
  • 今日观点:你永远无法改变别人,你只能改变你自己。你只有通过改变自己的方式,改变别人。 这句话听过无数次,也跟下属谈...
    杨雪雪阅读 300评论 6 1
  • 旅行最惊喜的莫过于遇见不同的人。 我不是旅行,而是离开与到达。南京,成都,往往返返。但难得的,往返的路途里也得...
    阿喵爱喝牛奶阅读 177评论 0 0