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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,870評論 0 10
  • 朋友雯長相清秀,性格落落大方、有想法,在工作上堅(jiān)持5年獲得部門經(jīng)理職位,事業(yè)順風(fēng)順?biāo)乃?,感情卻異常晚熟 ,一不著...
    無法抗拒的溫暖閱讀 367評論 0 0
  • 30天產(chǎn)品強(qiáng)化訓(xùn)練之觀察篇 三相同 1、都做了社區(qū)。 2、都是針對健身人群; 3、 社區(qū)用戶日志詳情頁基本架構(gòu)相同...
    Hans長夜下閱讀 587評論 0 1
  • 今日觀點(diǎn):你永遠(yuǎn)無法改變別人,你只能改變你自己。你只有通過改變自己的方式,改變別人。 這句話聽過無數(shù)次,也跟下屬談...
    楊雪雪閱讀 342評論 6 1
  • 旅行最驚喜的莫過于遇見不同的人。 我不是旅行,而是離開與到達(dá)。南京,成都,往往返返。但難得的,往返的路途里也得...
    阿喵愛喝牛奶閱讀 205評論 0 0

友情鏈接更多精彩內(nèi)容