當前位置:
首頁 >
Leet Code OJ 112. Path Sum [Difficulty: Easy]
發布時間:2024/2/28
35
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 112. Path Sum [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
翻譯:
給定一個二叉樹和一個和sum,檢測這個二叉樹是否存在一個從根節點到葉子節點的路徑,每個節點的和加起來是sum。
分析:
這道題目實現起來并不復雜,但有一些特殊取值的定義,題目說的不是很清楚,比如是空樹的時候,返回什么,根據OJ的結果,空樹是直接返回false的。還有一個可能出錯的地方是在葉子節點的判斷上,例如”[1,2] sum=1”這個輸入,”1”這個節點有左子樹”2”而沒有右子樹,而計算到”1” 這個節點時值剛剛是sum的1,筆者的第一版程序返回了true,但實際上這個節點并不是一個葉子節點。
代碼:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {public boolean hasPathSum(TreeNode root, int sum) {if(root==null){return false;}else{if(root.left==null&&root.right==null&&sum==root.val){return true;}if(hasPathSum(root.left, sum-root.val)){return true;}if(hasPathSum(root.right, sum-root.val)){return true;}}return false;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 112. Path Sum [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 101. Sy
- 下一篇: Leet Code OJ 237. De