-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraversalclass.java
More file actions
98 lines (81 loc) · 2.48 KB
/
traversalclass.java
File metadata and controls
98 lines (81 loc) · 2.48 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
91
92
93
94
95
96
97
98
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.mycompany.traversal;
/**
*
* @author HP
*/
class Node {
int data;
Node leftChild;
Node rightChild;
public Node(int data) {
this.data = data;
this.leftChild = null;
this.rightChild = null;
}
}
public class traversalclass {
Node root = null;
public void insert(int data) {
Node newNode = new Node(data);
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (data < current.data) {
current = current.leftChild;
if (current == null) {
parent.leftChild = newNode;
return;
}
} else {
current = current.rightChild;
if (current == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
public Node search(int data) {
Node current = root;
System.out.print("Visiting elements: ");
while (current != null && current.data != data) {
System.out.print(current.data + " ");
if (data < current.data) {
current = current.leftChild;
} else {
current = current.rightChild;
}
}
return current;
}
public void preOrderTraversal(Node node) {
if (node != null) {
System.out.print(node.data + " ");
preOrderTraversal(node.leftChild);
preOrderTraversal(node.rightChild);
}
}
public void inOrderTraversal(Node node) {
if (node != null) {
inOrderTraversal(node.leftChild);
System.out.print(node.data + " ");
inOrderTraversal(node.rightChild);
}
}
public void postOrderTraversal(Node node) {
if (node != null) {
postOrderTraversal(node.leftChild);
postOrderTraversal(node.rightChild);
System.out.print(node.data + " ");
}
}
}