Tree quetions
This post focuses only on programming questions related to tree dats it.
- TreeNode class will contain one integer data and two references for its left and right tree node.
Structure of Tree Node
1
2
3
4
5
6
7
8
9
10
11
|
package com.tachyon.basic;
public class TreeNode {
int data;
TreeNode left,right;
TreeNode(int data){
this.data = data;
left = right = null;
}
}
|
Basic Tree Traversals
- InOrder Traversal (Left Root Right)
1
2
3
4
5
6
7
8
|
public static void inOrderTraversal(TreeNode root) {
if(root != null) {
inOrderTraversal(root.left);
System.out.println(root.data);
inOrderTraversal(root.right);
}
}
|
- PreOrder Traversal (Root Left Right)
1
2
3
4
5
6
7
8
|
public static void preOrderTraversal(TreeNode root) {
if(root != null) {
System.out.println(root.data);
inOrderTraversal(root.left);
inOrderTraversal(root.right);
}
}
|
- PostOrder Traversal (Left Right Root)
1
2
3
4
5
6
7
8
|
public static void postOrderTraversal(TreeNode root) {
if(root != null) {
inOrderTraversal(root.left);
inOrderTraversal(root.right);
System.out.println(root.data);
}
}
|
- Insertion in a Binary tree
while inserting in binary tree we will check whether the number is greater or smaller than root data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public static void insert(int num) {
insertion(root,num);
}
public static TreeNode insertion(TreeNode root,int number) {
if(root == null) {
TreeNode newNode = new TreeNode(number);
return newNode;
}
if(number < root.data) {
root.left = insertion(root.left,number);
}
else {
root.right = insertion(root.right,number);
}
return root;
}
|
Questions on Ideserve site
Comments