Binary Tree:
–>Binary tree is a hierarchical data structure where each node has at most 2 children left child and right child
Tree Terminology:
Node: An element in the tree. It contains data and links
Root: The topmost node in the tree(No parent)
Parent: A Node that has children
Child: A node that is descendant of a parent node
Left child: The left connection from a parent node
Right child: The right connection from a parent node
Leaf node: A node with no children
Classroom Logo
Notification settings
AS College Prefinal years
New announcement
/*Binary Tree:
–>Binary tree is a hierarchical data structure where each node has at most 2 children left child and right child
Tree Terminology:
Node: An element in the tree. It contains data and links
Root: The topmost node in the tree(No parent)
Parent: A Node that has children
Child: A node that is descendant of a parent node
Left child: The left connection from a parent node
Right child: The right connection from a parent node
Leaf node: A node with no children
——————————————————————*/
//create a node
class Node
{
int key;
Node left,right;//Node next
public Node(int item)//item=4
{
key=item;//key=4
left=right=null;
}
}
class BinaryTree
{
Node root;//Node head;
public void traverseTree(Node node)//root node
{
if(node!=null)
{
traverseTree(node.left);
System.out.println(” “+node.key);
traverseTree(node.right);
}
}
public static void main(String args[])
{
Binarytree tree=new BinaryTree();
//creates node of the tree
tree.root=new Node(1);
tree.root.left=new Node(2);
tree.root.right=new Node(3);
tree.root.left.left=new Node(4);
tree.traverseTree(tree.root);
}
}
/*Tree traversal means visiting every node in a tree exactly once–>Depth first search, Breadth first search
DFS–>Preorder, postorder, Inorder
BFS–>visits the tree level by level from top to bottom*/
Preorder–>Root–>Left–>Right
Inorder–>Left–>Root–>Right
PostOrder–>Left–>Right–>Root
———————————–
Inorder://4–>2–>1–>3
if(node!=null)
{
traverseTree(node.left);
System.out.println(” “+node.key);
traverseTree(node.right);
}
Preorder://4–>2–>3–>1
if(node!=null)
{
System.out.println(” “+node.key);
traverseTree(node.left);
traverseTree(node.right);
}
Postorder://1–>2–>4–>3
if(node!=null)
{
traverseTree(node.left);
traverseTree(node.right);
System.out.println(” “+node.key);
}