0
0
DSA Typescriptprogramming~15 mins

Binary Tree Node Structure in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Binary Tree Node Structure
📖 Scenario: You are building a simple binary tree to store numbers. Each spot in the tree can hold one number and can have up to two smaller spots connected to it: one on the left and one on the right.
🎯 Goal: Create a basic binary tree node structure in TypeScript. You will first define the node with its value and connections, then create a simple tree with three nodes.
📋 What You'll Learn
Define a class called TreeNode with three properties: value, left, and right.
The value should be a number.
The left and right should be either another TreeNode or null.
Create three nodes with values 10, 5, and 15.
Connect the nodes so that 10 is the root, 5 is the left child, and 15 is the right child.
💡 Why This Matters
🌍 Real World
Binary trees are used in many applications like searching, sorting, and organizing data efficiently.
💼 Career
Understanding binary tree structures is fundamental for software developers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Define the TreeNode class
Create a class called TreeNode with a constructor that takes a value of type number. Inside the constructor, set this.value to the given value. Also, add two properties left and right initialized to null.
DSA Typescript
Hint

Remember to set this.value to the input value. Initialize left and right to null.

2
Create three TreeNode instances
Create three variables called root, leftChild, and rightChild. Assign them new TreeNode objects with values 10, 5, and 15 respectively.
DSA Typescript
Hint

Use new TreeNode(value) to create each node and assign to the correct variable.

3
Connect the nodes to form the tree
Set the left property of root to leftChild and the right property of root to rightChild.
DSA Typescript
Hint

Use dot notation to set root.left and root.right.

4
Print the tree node values
Print the values of root, root.left, and root.right using console.log. Print them in this order, separated by spaces.
DSA Typescript
Hint

Use console.log(root.value, root.left?.value, root.right?.value) to print the values separated by spaces.