[LeetCode]Path Sum
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.
题挺水的,不过刚开始一直wa了几次,发觉基础真的好重要,我把leaf这个概念弄混了.我刚开始只是判断有一条路某时刻满足条件就判断true了,结果就wa了好几次.
leaf的定义是左右子节点都为空!!!
code
public class Solution { public boolean hasPathSum( TreeNode root, int sum ) { if( root != null ) { sum -= root.val; if( sum == 0 && root.left == null && root.right == null ) return true; else return hasPathSum( root.left, sum ) || hasPathSum( root.right, sum ); } else return false; } public static void main( String[] args ) { Solution s = new Solution(); TreeNode root = new TreeNode( 5 ); root.left = new TreeNode( 4 ); root.left.left = new TreeNode( 11 ); root.left.left.left = new TreeNode( 7 ); root.left.left.right = new TreeNode( 2 ); root.right = new TreeNode( 8 ); root.right.left = new TreeNode( 13 ); root.right.right = new TreeNode( 4 ); root.right.right.right = new TreeNode( 1 ); // root.left = new TreeNode( 1 ); System.out.println( s.hasPathSum( root, 9 ) ); } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode( int x ) { val = x; } }