0
0
DSA Goprogramming~30 mins

Create a Binary Tree Manually in DSA Go - Build from Scratch

Choose your learning style9 modes available
Create a Binary Tree Manually
📖 Scenario: You are building a simple binary tree to organize numbers. Each node can have up to two children: left and right. This structure helps in searching and sorting numbers efficiently.
🎯 Goal: Create a binary tree manually by defining nodes and linking them. Then print the tree nodes in a simple order to see the structure.
📋 What You'll Learn
Define a struct called Node with an integer value and two pointers left and right to Node.
Create nodes with exact values: 10, 5, 15, 3, 7.
Link nodes to form the binary tree: 10 as root, 5 as left child, 15 as right child, 3 as left child of 5, 7 as right child of 5.
Write a function to print the tree nodes in pre-order (root, left, right).
Print the values of the tree nodes in pre-order.
💡 Why This Matters
🌍 Real World
Binary trees are used in many applications like organizing data, searching quickly, and managing hierarchical information such as file systems or decision trees.
💼 Career
Understanding how to create and traverse binary trees is fundamental for software developers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Define the Node struct and create nodes
Define a struct called Node with an integer field value and two pointer fields left and right of type *Node. Then create five variables called root, node5, node15, node3, and node7 of type Node with values 10, 5, 15, 3, and 7 respectively.
DSA Go
Hint

Start by defining the Node struct with the fields. Then create variables for each node with the given values.

2
Link nodes to form the binary tree
Link the nodes to form the binary tree by setting root.left to the address of node5, root.right to the address of node15, node5.left to the address of node3, and node5.right to the address of node7.
DSA Go
Hint

Use the & operator to get the address of the nodes and assign them to the left and right pointers.

3
Write a function to print the tree in pre-order
Write a function called preOrderPrint that takes a pointer to Node called node. It should print the value of node, then recursively call itself on node.left and node.right if they are not nil.
DSA Go
Hint

Check if the node is nil to stop recursion. Print the node's value, then call the function on left and right children.

4
Print the tree nodes in pre-order
Call the function preOrderPrint with the address of root in main. Then print a newline using fmt.Println().
DSA Go
Hint

Call preOrderPrint(&root) to start printing from the root node. Use fmt.Println() to add a newline after printing.