- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to traverse a given binary tree in Preorder Traversal (Recursive)
Example
Suppose we have the following binary tree.
Preorder Tree Traversal Output: 1, 2, 4, 5, 3, 6, 7.
Approach to solve this problem
Step 1 − If the root node of the given tree is nil, then return; else, follow the steps given below.
Step 2 − Print the root node data.
Step 3 − Traverse the Left sub-tree.
Step 4 − Traverse the Right sub-tree.
Example
package main import "fmt" type Node struct { data int left *Node right *Node } func (root *Node)PreOrderTraversal(){ if root !=nil{ fmt.Printf("%d ", root.data) root.left.PreOrderTraversal() root.right.PreOrderTraversal() } return } func main(){ tree := Node{1, &Node{2, &Node{4, nil, nil}, &Node{5, nil, nil}}, &Node{3, &Node{6, nil, nil}, &Node{7, nil, nil}}} fmt.Printf("Pre Order Traversal of the given tree is: ") tree.PreOrderTraversal() }
Output
Pre Order Traversal of the given tree is: 1 2 4 5 3 6 7
- Related Articles
- Golang Program to traverse a given tree in Postorder Traversal (Recursive).
- Golang program to traverse a given tree in Inorder Traversal (Recursive).
- C++ Program to Perform Preorder Recursive Traversal of a Given Binary Tree
- C++ Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
- Golang Program to Perform the preorder tree traversal
- Binary Tree Preorder Traversal in Python
- C++ Program to Perform Inorder Recursive Traversal of a Given Binary Tree
- C++ Program to Perform Postorder Recursive Traversal of a Given Binary Tree
- C++ Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
- C++ Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
- Construct Binary Search Tree from Preorder Traversal in Python
- Check if a given array can represent Preorder Traversal of Binary Search Tree in C++
- Construct Binary Tree from Preorder and Inorder Traversal in Python
- Construct Binary Tree from Preorder and Postorder Traversal in Python
- Find n-th node in Preorder traversal of a Binary Tree in C++

Advertisements