-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
90 lines (61 loc) · 1.41 KB
/
Copy pathBinaryTree.java
File metadata and controls
90 lines (61 loc) · 1.41 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.ravi.tree;
public class BinaryTree {
int data;
BinaryTree left;
BinaryTree right;
public BinaryTree(int data) {
this.data = data;
this.left = null;
this.right = null;
}
public static void main(String[] args) {
BinaryTree bt1 = new BinaryTree(1);
BinaryTree bt2 = new BinaryTree(2);
BinaryTree bt3 = new BinaryTree(3);
BinaryTree bt4 = new BinaryTree(4);
BinaryTree bt5 = new BinaryTree(5);
BinaryTree bt6 = new BinaryTree(6);
BinaryTree bt7 = new BinaryTree(7);
bt1.left = bt2;
bt1.right = bt3;
bt2.left = bt4;
bt2.right = bt5;
bt3.left = bt6;
bt3.right = bt7;
inOrder(bt1);
reverseTree(bt1);
System.out.println("reversed");
inOrder(bt1);
}
public static void inOrder(BinaryTree root){
BinaryTree current = root;
if(current.left != null ){
inOrder(current.left);
}
System.out.println(current.data);
if(current.right != null ){
inOrder(current.right);
}
}
public static BinaryTree reverseTree(BinaryTree root){
BinaryTree current = root;
if( current == null){
return null;
}
else{
swap(current);
}
return current;
}
public static void swap(BinaryTree current){
BinaryTree temp = current.left;
current.left = current.right;
current.right = temp;
if(current.left != null){
swap(current.left);
}
if(current.right != null){
swap(current.right);
}
}
}