Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*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,
- */
- /**
- * 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 inorder(root,sum,0);
- return false;
- }
- public static boolean inorder (TreeNode root,int sum,int current_sum)
- {
- if(root!=null)
- {
- if(root.left==null&&root.right==null&&sum==(current_sum+root.val))
- return true;
- return inorder(root.left,sum,(current_sum+root.val))||inorder(root.right,sum,current_sum+root.val);
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment