原题链接在这里:
题目:
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 andsum = 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.
题解:
减掉当前节点值,判断是不是叶子节点同时满足sum==0即可。
Time Complexity: O(n), worst case是每个node都跑了一次.
Space: O(logn), stack space.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 public boolean hasPathSum(TreeNode root, int sum) {12 if(root == null){13 return false;14 }15 sum-=root.val;16 if(root.left == null && root.right == null && sum == 0){17 return true;18 }else{19 return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);20 }21 }22 }
跟上, , .