-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSibling(Binary Tree)
72 lines (55 loc) · 1.2 KB
/
Sibling(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
import java.util.*;
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();
bt.sibling();
}
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 sibling() {
this.sibling(this.root);
}
private void sibling(Node node) {
if(node == null){
return;
}
if(node.left!= null && node.right==null){
System.out.print(node.left.data+" ");
}
else if(node.left==null && node.right!=null){
System.out.print(node.right.data+" ");
}
sibling(node.left);
sibling(node.right);
}
}
}