Tree - means root, parent and child nodes, leaf nodes
Root - at the top of the Tree
Internal Nodes - parent and child
Leaf - Nodes at the end of the tree
Binary Tree - At most 0,1, 2 child nodes.
Full Binary Tree/Strict Binary Tree - 0 or 2 Children.
ACBT Almost Complete Binary Tree :
1. Complete the tree with Left to Right
2. Complete the tree with level
Complete Binary Tee : Except children at leaf every level needs to filled with children
Binary Search Tree: height = log(n)
Inserted Left element are need to smaller and Right element need to greater.
How to insert and traverse the Binary search tree:
Right side nodes will be greater than root
Left side nodes will be less than root
Pre Order, In Order, Post Order:
InOrder - Left Root Right
PreOrder - Root Left Right
Post Order - Left Right Root
import java.util.Scanner;
class tree {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) {
Node root = createTree();
inOrder(root);
System.out.println();
preOrder(root);
System.out.println();
postOrder(root);
}
static Node createTree() {
Node root = null;
System.out.println("Enter the data");
int data = sc.nextInt();
if (data == -1) {
return null;
}
root = new Node(data);
System.out.println("Enter the left " + data);
root.left = createTree();
System.out.println("Enter the right" + data);
root.right = createTree();
return root;
}
static void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
static void preOrder(Node root) {
if (root == null) {
return;
}
System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
static void postOrder(Node root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + " ");
}
}
class Node {
Node left;
Node right;
int data;
Node(int d) {
this.data = d;
}
}
Input :
2 4 7 -1 -1 -1 1 8 -1 -1 3 -1 -1
Output:
Video Reference:
Anuj Bhaiya :
Implementation : https://www.youtube.com/watch?v=QhIM-G7FAow
Traversal Techniques : https://www.youtube.com/watch?v=cFRRgwPIk2s
No comments:
Post a Comment