1) Traverse Tree in PreOrder with recursion:
i/p:
pass values as,
root-1, root.left=2, root.right=3, root.left.right=4,root.right.left=5
o/p:
root = 1
root->left = 2
root->left->right = 4
root->right = 3
root->right->left = 5
using System;
//Node Creation
class Node{
public int value;
public Node left, right;
public Node(int n){
value=n;
left=right=null;
}
}
class HelloWorld {
Node root=null;
static void Main() {
HelloWorld obj=new HelloWorld();
//input passing
obj.root=new Node(1);
obj.root.left=new Node(2);
obj.root.right=new Node(3);
obj.root.left.right=new Node(4);
obj.root.right.left=new Node(5);
//call & print in preOrderTraversal
obj.preOrderTraversal("root",obj.root);
}
void preOrderTraversal(string info,Node root) {
if(root==null) return;
Console.WriteLine("{0} = {1} ",info,root.value);
preOrderTraversal(info+"->left",root.left);
preOrderTraversal(info+"->right",root.right);
}
}
2) Traverse Tree in PreOrder without recursion:
Algorithm:
1) create an empty stack
2) push root node
3) run the loop till the stack is empty
4) pop the topmost element from the stack then print its value
5) push the left or right node into a stack-based on its value
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
class Node
{
public int value;
public Node left,right;
public Node(int n)
{
value=n;
left=right=null;
}
}
class GFG
{
public void preOrderTraversal(Node root)
{
Stack<Node> st=new Stack<Node>();
st.Push(root);
while(st.Any()){
Node current=st.Pop();
Console.WriteLine(current.value);
if(current.left!=null){
st.Push(current.left); }
if(current.right!=null) {
st.Push(current.right); } }
}
Node root=null;
static void Main ()
{
GFG obj=new GFG();
obj.root=new Node(1);
obj.root.left=new Node(2);
obj.root.right=new Node(3);
obj.preOrderTraversal(obj.root);
}
}
o/p:
1
3
2
No comments:
Post a Comment