📖 Scenario: You are building a simple binary tree to organize numbers. Each spot in the tree can hold one number and can connect to two other spots: one on the left and one on the right.
🎯 Goal: Create a basic binary tree node structure in Rust that can hold a number and links to left and right child nodes.
📋 What You'll Learn
Define a struct called TreeNode with three fields: value, left, and right.
The value field should hold an i32 number.
The left and right fields should be Option> to allow for empty or existing child nodes.
💡 Why This Matters
🌍 Real World
Binary trees are used in many places like organizing data for quick search, sorting, and managing hierarchical information.
💼 Career
Understanding how to build and use binary trees is important for software development roles that involve data structures, algorithms, and system design.
Progress0 / 4 steps
1
Define the TreeNode struct
Define a public struct called TreeNode with a field value of type i32.
DSA Rust
Hint
Use pub struct TreeNode and add a field value: i32.
2
Add left and right child nodes
Add two public fields to TreeNode called left and right. Both should be of type Option>.
DSA Rust
Hint
Use Option> for both left and right fields.
3
Create a new TreeNode instance
Create a function called new inside an impl TreeNode block that takes an i32 parameter called value and returns a TreeNode with left and right set to None.
DSA Rust
Hint
Define impl TreeNode and inside it a pub fn new(value: i32) -> Self that returns a TreeNode with left and right as None.
4
Print the root node value
Create a main function. Inside it, create a variable called root by calling TreeNode::new(10). Then print the value of root using println!.
DSA Rust
Hint
Use let root = TreeNode::new(10); and then println!("{}", root.value); inside main.
Practice
(1/5)
1. What does a binary tree node typically contain in its structure?
easy
A. A value and a pointer to the next node in a list
B. Only a value without any pointers
C. Pointers to parent and sibling nodes only
D. A value and pointers to left and right child nodes
Solution
Step 1: Understand binary tree node components
A binary tree node stores data and links to two children: left and right.
Step 2: Compare options with definition
Only A value and pointers to left and right child nodes correctly describes a node with value and two child pointers.
Final Answer:
A value and pointers to left and right child nodes -> Option D
Quick Check:
Binary tree node = value + left/right pointers [OK]
Hint: Remember: binary tree nodes have two child links [OK]
Common Mistakes:
Thinking nodes have only one child pointer
Confusing with linked list node structure
Assuming nodes store parent pointers by default
2. Which of the following is the correct Rust syntax to define a binary tree node struct with integer value and optional children?