How to implement PreOrder Traversal in Binary Tree?
💻 coding

How to implement PreOrder Traversal in Binary Tree?

1 min read 174 words
1 min read
ShareWhatsAppPost on X
  • 1Pre-order traversal processes each node before its subtrees, making it a straightforward method to understand.
  • 2The traversal follows a specific order: visit the root, traverse the left subtree, then the right subtree.
  • 3A Java implementation of pre-order traversal is provided, demonstrating how to print node values in the correct order.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Pre-order traversal processes each node before its subtrees, making it a straightforward method to understand."

How to implement PreOrder Traversal in Binary Tree?

In pre-order traversal, each node is processed before (pre) either of it's sub-trees. This is the simplest traversal to understand. However, even though each node is processed before the subtrees, it still requires that some information must be maintained while moving down the tree.

Preorder traversal is defined as follows:

- Visit the root.

- Traverse the left subtree in Preorder.

- Traverse the right subtree in Preorder.

Java code for above implement is as below:

package askgif.tree;

class Node
{
 int data;
 Node left, right;
 
 public Node(int item)
 {
 data = item;
 left = right = null;
 }
}

class BinaryTree
{
 Node root;
 
 BinaryTree()
 {
 root = null;
 }
 
}

public class TreeQuestions {

	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		Node root = new Node(1);
		binaryTree.root = root;
		binaryTree.root.left = new Node(2);
		binaryTree.root.right = new Node(3);
		binaryTree.root.left.left = new Node(4);
		binaryTree.root.left.right = new Node(5);
 
 PrintPreOrderTraversal(root);

	}

	private static void PrintPreOrderTraversal(Node treeNode) {
		if(treeNode == null)
			return;
		System.out.println(treeNode.data);
		PrintPreOrderTraversal(treeNode.left);
		PrintPreOrderTraversal(treeNode.right);
		
	}

}
output:

1
2
4
5
3

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 9 August 2018 · 1 min read · 174 words

Part of AskGif Blog · coding

You might also like

How to implement PreOrder Traversal in Binary Tree? | AskGif Blog