1. 程式人生 > >112. Path Sum二叉樹路徑和

112. Path Sum二叉樹路徑和

aps exist display splay term post ase urn 數據結構

[抄題]:

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.

[暴力解法]:

時間分析:

空間分析:

[奇葩輸出條件]:

字符串中間還要加符號,頭一次見

[奇葩corner case]:

兩端都是空,只有root一個點也是能求和的,第一次見。下次二叉樹求和的時候只要有點就能加

[思維問題]:

不知道怎麽利用sum:變成參數即可

[一句話思路]:

還是沒有匯總的traverse,把sum參與進來,把sum參數化變成一個參數就行了

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

[復雜度]:Time complexity: O(n) Space complexity: O(n)

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

path sum後續系列

[代碼風格] :

技術分享圖片
/**
 * 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) { //root is null if (root == null) { return false; } //only root is not null if (root.left == null && root.right == null) { return root.val == sum; } //remaning sum in left or sum in right return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)); } }
View Code

112. Path Sum二叉樹路徑和