- Root – Root is a special node in a tree. The entire tree is referenced through it. It does not have a parent.
- Parent Node – Parent node is an immediate predecessor of a node.
- Child Node – All immediate successors of a node are its children.
- Siblings – Nodes with the same parent are called Siblings.
- Leaf – Last node in the tree. There is no node after this node.
- Edge – Edge is a connection between one node to another. It is a line between two nodes or a node and a leaf.
- Path – Path is a number of successive edges from source node to destination node.
- Tree can be termed as a RECURSIVE data structure.
- In a valid tree for N Nodes we have N-1 Edges/Links
- Depth (or LEVEL) of Node – Depth of a node represents the number of edges from the tree’s root node to the node.
- Height of Node – Height of a node is the number of edges on the longest path between that node & a leaf.
- Height of Tree – Height of tree represents the height of its root node.
A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child(LC) and the right child(RC).
- Strict/Proper BT - Binary tree where each node has 2 or 0 children.
- Complete BT - Binary tree where all levels except the last are completely filled orelse if any levels are partially filled then all nodes in that level should be as left as possible.
- Perfect BT - Binary tree where each node has 2 childrens, except leaf nodes.
- Balance BT - Binary tree where the difference between the height of left subtree and right subtree for every node is not more than k(usually k=1). Travesal in balanced BT is more efficient than unbalanced BT.
- Max number of nodes at a given level ‘x’ = 2^x
- For a binary tree, maximum number of nodes with height ‘h’ = 2(h+1) – 1
public class BinaryTree {
public static void main(String args[]) {
Node root=new Node(1);
root.left=new Node(2);
root.right=new Node(3);
/* 1
/ \
2 3
*/
root.left.left=new Node(4);
root.left.right=new Node(5);
/* 1
/ \
2 3
/ \
4 5
*/
root.right.left=new Node(6);
root.right.right=new Node(7);
/* 1
/ \
2 3
/ \ / \
4 5 6 7
*/
}
}
class Node{
int data;
Node left;
Node right;
public Node(int val) {
data=val;
left=right=null;
}
}