-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroot to leaf(Binary Tree)
73 lines (56 loc) · 1.36 KB
/
root to leaf(Binary Tree)
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
package assignment;
import java.util.Scanner;
public class Main {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
Main m = new Main();
BinaryTree bt = m.new BinaryTree();
int T = scn.nextInt();
bt.rootleaf(T);
}
private class BinaryTree {
private class Node {
int data;
Node left;
Node right;
}
private Node root;
private int size;
public BinaryTree() {
this.root = this.takeInput(null, false);
}
public Node takeInput(Node parent, boolean ilc) {
int cdata = scn.nextInt();
Node child = new Node();
child.data = cdata;
this.size++;
// left
boolean hlc = scn.nextBoolean();
if (hlc) {
child.left = this.takeInput(child, true);
}
// right
boolean hrc = scn.nextBoolean();
if (hrc) {
child.right = this.takeInput(child, false);
}
// return
return child;
}
public void rootleaf(int T) {
this.rootleaf(this.root, 0, T, "");
}
private void rootleaf(Node node, int sum, int T, String str) {
if (sum + node.data == T && node.left == null && node.right == null) {
System.out.println(str + node.data);
return;
}
else if( node.left ==null && node.right == null) {
return;
}
sum = sum + node.data;
rootleaf(node.left, sum, T, str + "" + node.data + " ");
rootleaf(node.right, sum, T, str + "" + node.data + " ");
}
}
}