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,424評論 0 10
  • 朋友雯長相清秀,性格落落大方、有想法,在工作上堅持5年獲得部門經理職位,事業順風順水的她,感情卻異常晚熟 ,一不著...
    無法抗拒的溫暖閱讀 325評論 0 0
  • 30天產品強化訓練之觀察篇 三相同 1、都做了社區。 2、都是針對健身人群; 3、 社區用戶日志詳情頁基本架構相同...
    Hans長夜下閱讀 531評論 0 1
  • 今日觀點:你永遠無法改變別人,你只能改變你自己。你只有通過改變自己的方式,改變別人。 這句話聽過無數次,也跟下屬談...
    楊雪雪閱讀 291評論 6 1
  • 旅行最驚喜的莫過于遇見不同的人。 我不是旅行,而是離開與到達。南京,成都,往往返返。但難得的,往返的路途里也得...
    阿喵愛喝牛奶閱讀 169評論 0 0