Coding Challenge Day- 33: Problem 1: Pre-order Traversal of a Binary Tree

Hello! So I’m doing a 100 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 33: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem: Pre-order Traversal of a Binary Tree

Algorithm Logic:

1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)

Solution:

View on/ Download from Github: (LINK)

package binary_tree;

public class Preorder_traversal {
		
		static class Node{
			
			int data;
			Node left_child, right_child;
			
			public Node(int d){
				data= d;
				left_child= right_child=null;
			}
		}
		
		static class Binary_tree{
			Node root;
			
			public Binary_tree (){
				root= null;
			}
			
			public void add_left_node (Node parent_node, Node node){
				parent_node.left_child= node;
			}
			
			public void add_right_node (Node parent_node, Node node){
				parent_node.right_child=node;
			}
			
			public void preorder_traversal (Node node){
				if(node==null)
					return;
				
				System.out.print(node.data+ " ");
				preorder_traversal(node.left_child);
				preorder_traversal(node.right_child);
			}
			
		}
		
		public static void main (String [] args){
			Binary_tree t= new Binary_tree();
			
			t.root= new Node(10);
			
			Node node11= new Node(20);
			t.add_left_node(t.root, node11);
			
			Node node12= new Node(30);
			t.add_right_node(t.root, node12);
			
			Node node111= new Node(40);
			t.add_left_node(node11, node111);
			
			Node node112= new Node(50);
			t.add_right_node(node11, node112);
			
			t.preorder_traversal(t.root);
		}

}

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close