Java程式碼 給出一個二叉樹和一個數,判斷該二叉樹是否存在一個從根節點到葉節點的和與給出的數相同
阿新 • • 發佈:2018-12-29
從菜鳥到大牛一定要戒驕戒躁,沉下心來慢慢打磨自己!
這個題目的演算法思想分為三種情況:
case1樹為空時,返回false
case2 樹只有一個根節點
case3 正常情況下的樹
Java程式碼如下:
/**
* 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) {
//case1 the tree is null
if(root==null)return false;
//case2 the tree has only one node
sum=sum-root.val;
if((root.left==null)&&(root.right==null))return sum==0;
//case3 nomal case
return hasPathSum(root.left,sum)||hasPathSum(root.right,sum);
}
}