Problem Statement:
Remove the paths from root to leaf whose sum is not equal to given K.
Given Sum = 15 = K
Source Code
Solution:
Valid paths with given sum :
1 - > 2 - > 4 - > 8
and 1 - > 3 - > 6 - > 5
Bottom - up approach is being used to prune to the tree.
Below is the implementation.
Please post your comments and suggestions.
Happy Coding !! :)
Remove the paths from root to leaf whose sum is not equal to given K.
Given Sum = 15 = K
Source Code
Solution:
Valid paths with given sum :
1 - > 2 - > 4 - > 8
and 1 - > 3 - > 6 - > 5
Bottom - up approach is being used to prune to the tree.
Below is the implementation.
public static boolean prunePath(Node root, int givenSum , int currSum) { if(root==null) { if(givenSum==currSum) return true; else return false; } boolean leftFlag = prunePath(root.left , givenSum , currSum+root.data); boolean rightFlag = prunePath(root.right , givenSum , currSum+root.data); if(!leftFlag) root.left=null; if(!rightFlag) root.right=null; return (leftFlag || rightFlag ) ; }
Please post your comments and suggestions.
Happy Coding !! :)