class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
public class TreeTraversalInOrderAndDisplay {
// Root of Binary Tree
Node root;
TreeTraversalInOrderAndDisplay() { root = null; }
/* Given a binary tree, print its nodes in inorder*/
void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.key + " ");
/* now recur on right child */
printInorder(node.right);
}
// Wrappers over above recursive functions
void printInorder() { printInorder(root); }
// Driver code
public static void main(String[] args)
{
TreeTraversalInOrderAndDisplay tree = new TreeTraversalInOrderAndDisplay();
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.root.left.right = new Node(5);
// Function call
System.out.println(
"\nTraversal of binary tree is ");
tree.printInorder();
//Time Complexity: O(N)
//Auxiliary Space: If we don’t consider the size of the stack for function
// calls then O(1) otherwise O(h) where h is the height of the tree.
}
}
TechInsiderStory is place where you can find basic knowledge of various technology and framework. TechInsiderStory is provide free knowledge on various technology and framework.
Tree Traverse In Order Recursive Approach And Display
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment