-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathBinary Search Trees:Path Sum Root to Leaf
77 lines (69 loc) · 2.06 KB
/
Binary Search Trees:Path Sum Root to Leaf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class Solution {
// /* Binary Tree Node class
// *
// * class BinaryTreeNode<T> {
// T data;
// BinaryTreeNode<T> left;
// BinaryTreeNode<T> right;
// public BinaryTreeNode(T data) {
// this.data = data;
// }
// }
// */
public static void rootToLeafPathsSumToK(BinaryTreeNode<Integer> root, int k) {
// Write your code here
helper(root,k,"");
}
private static void helper(BinaryTreeNode<Integer> root,int k,String s){
if(root==null)
return;
if(root.left==null && root.right==null && root.data==k)
{
System.out.println(s+root.data);
return;
}
s=s+root.data+" ";
helper(root.left,k-root.data,s);
helper(root.right,k-root.data,s);
}
}
// public class Solution {
// /* Binary Tree Node class
// *
// * class BinaryTreeNode<T> {
// T data;
// BinaryTreeNode<T> left;
// BinaryTreeNode<T> right;
// public BinaryTreeNode(T data) {
// this.data = data;
// }
// }
// */
// public static void rootToLeafPathsSumToK(BinaryTreeNode<Integer> root, int k,String ans) {
// if(k==root.data){
// if(root.right==null&&root.left==null){
// System.out.println(ans+" "+root.data);
// return;
// }else{
// return;
// }
// }
// if(root.left!=null){
// if(ans=="")
// rootToLeafPathsSumToK(root.left ,k-root.data,ans+root.data);
// else{
// rootToLeafPathsSumToK(root.left ,k-root.data,ans+" "+root.data);
// }
// }
// if(root.right!=null){
// if(ans=="")
// rootToLeafPathsSumToK(root.right ,k-root.data,ans+root.data);
// else{
// rootToLeafPathsSumToK(root.right ,k-root.data,ans+" "+root.data);
// }
// }
// }
// public static void rootToLeafPathsSumToK(BinaryTreeNode<Integer> root, int k) {
// rootToLeafPathsSumToK(root,k,"");
// }
// }