Created
May 4, 2024 11:39
-
-
Save tewari2312/e5e219a0a75576bd99453678733b457a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class RootToLeafPathSum { | |
| boolean result = false; | |
| int currentPathSum = 0; | |
| public static void main(String[] args) { | |
| TreeNode E1node7 = new TreeNode(7); | |
| TreeNode E1node2 = new TreeNode(2); | |
| TreeNode E1node1 = new TreeNode(1); | |
| TreeNode E1node11 = new TreeNode(11,E1node7, E1node2); | |
| TreeNode E1node13 = new TreeNode(13); | |
| TreeNode E1node4_R = new TreeNode(4, null, E1node1); | |
| TreeNode E1node8 = new TreeNode(8, E1node13, E1node4_R); | |
| TreeNode E1node4_L = new TreeNode(4, E1node11, null); | |
| TreeNode E1node5 = new TreeNode(5,E1node4_L,E1node8); | |
| System.out.println(new RootToLeafPathSum().hasPathSum(E1node5, 22)); | |
| TreeNode E2nodeN1 = new TreeNode(-1); | |
| TreeNode E2node3 = new TreeNode(3); | |
| TreeNode E2nodeN2 = new TreeNode(-2); | |
| TreeNode E2nodeN3 = new TreeNode(-3, E2nodeN2, null); | |
| TreeNode E2node1_L = new TreeNode(1,E2nodeN1, null); | |
| TreeNode E2nodeN2_L = new TreeNode(-2, E2node1_L, E2node3); | |
| TreeNode E2node1 = new TreeNode(1, E2nodeN2_L, E2nodeN3); | |
| System.out.println(new RootToLeafPathSum().hasPathSum(E2node1, 2)); | |
| } | |
| public boolean hasPathSum(TreeNode root, int targetSum) { | |
| if(root!=null){ | |
| currentPathSum = currentPathSum + root.val; | |
| if(root.left==null && root.right==null){ | |
| if(targetSum == currentPathSum){ | |
| result = true; | |
| return result; | |
| }else | |
| currentPathSum = currentPathSum - root.val; | |
| }else{ | |
| if(root.left!=null) | |
| hasPathSum(root.left, targetSum); | |
| if(root.right!=null) | |
| hasPathSum(root.right, targetSum); | |
| currentPathSum = currentPathSum - root.val; | |
| } | |
| return result; | |
| } | |
| return result; | |
| } | |
| } | |
| class TreeNode { | |
| int val; | |
| TreeNode left; | |
| TreeNode right; | |
| TreeNode() {} | |
| TreeNode(int val) { this.val = val; } | |
| TreeNode(int val, TreeNode left, TreeNode right) { | |
| this.val = val; | |
| this.left = left; | |
| this.right = right; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment