-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree
More file actions
88 lines (68 loc) · 1.92 KB
/
Copy pathBinaryTree
File metadata and controls
88 lines (68 loc) · 1.92 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
package binaryTree;
class BinaryTreeNode {
public BinaryTreeNode(int val) {
this.val = val;
this.leftChild = null;
this.rightChild = null;
}
int val;
BinaryTreeNode leftChild;
BinaryTreeNode rightChild;
}
/**
* binary tree
*
* 1
* / \
* 2 3
* / \
* 4 5
*
* Depth First Traversals:
* (a) Inorder (Left, Root, Right) : 4 2 5 1 3
* (b) Preorder (Root, Left, Right) : 1 2 4 5 3
* (c) Postorder (Left, Right, Root) : 4 5 2 3 1
*
*
*
*/
public class BinaryTree {
public static void inorderTraversal(BinaryTreeNode root){
if (root == null){
return;
}
inorderTraversal(root.leftChild);
System.out.println(root.val);
inorderTraversal(root.rightChild);
}
public static void preOrderTraversal(BinaryTreeNode root){
if (root == null){
return;
}
System.out.println(root.val); // pre order
preOrderTraversal(root.leftChild);
preOrderTraversal(root.rightChild);
}
public static void postOrderTraversal(BinaryTreeNode root){
if (root == null){
return;
}
postOrderTraversal(root.leftChild);
postOrderTraversal(root.rightChild);
System.out.println(root.val);
}
public static void main(String[] args) {
BinaryTreeNode node1 = new BinaryTreeNode(1);
BinaryTreeNode node2 = new BinaryTreeNode(2);
BinaryTreeNode node3 = new BinaryTreeNode(3);
BinaryTreeNode node4 = new BinaryTreeNode(4);
BinaryTreeNode node5 = new BinaryTreeNode(5);
node1.leftChild = node2;
node1.rightChild = node3;
node2.leftChild = node4;
node2.rightChild = node5;
//preOrderTraversal(node1);
//inorderTraversal(node1);
postOrderTraversal(node1);
}
}