25、路徑總和
阿新 • • 發佈:2018-11-16
題目描述
我的思路:首先檢視的是根節點,然後用num-根節點的值,並且要考慮到節點是否為空
需要注意的是這裡的遞迴要注意,二叉樹基本都是遞迴來實現
//再一次使用遞迴 public static boolean hasPathSum(TreeNode root, int sum) { if(root == null){ return false; }else { int i = sum - root.val; if(root.left == null && root.right == null){ return i == 0? true:false; } return hasPathSum(root.left, i)||hasPathSum(root.right, i); } }
排名比較高的程式碼,我感覺思路都差不多,為什麼時間能差這麼多???
/** * 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 decide(root,sum); } public boolean decide(TreeNode root, int sum){ if(root==null){ return false; } if(root.left==null&&root.right==null&&root.val==sum){ return true; } return decide(root.left,sum-root.val)|| decide(root.right,sum-root.val); } }