0
0
DSA Javascriptprogramming~10 mins

Tree Terminology Root Leaf Height Depth Level in DSA Javascript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create the root node of a tree.

DSA Javascript
const root = new TreeNode([1]);
Drag options to blanks, or click blank then click option'
Anull
B0
C1
D'root'
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or 0 as the root value which may not represent the root meaningfully.
2fill in blank
medium

Complete the code to check if a node is a leaf (has no children).

DSA Javascript
function isLeaf(node) {
  return node.children.length [1] 0;
}
Drag options to blanks, or click blank then click option'
A===
B>
C<
D!==
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or !== which would not correctly identify leaf nodes.
3fill in blank
hard

Fix the error in the code to calculate the height of a tree node.

DSA Javascript
function height(node) {
  if (!node) return -1;
  let maxChildHeight = -1;
  for (const child of node.children) {
    maxChildHeight = Math.max(maxChildHeight, height(child));
  }
  return maxChildHeight [1] 1;
}
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication which gives wrong height values.
4fill in blank
hard

Fill both blanks to calculate the depth of a node given its parent depth.

DSA Javascript
function depth(node, parentDepth) {
  if (!node) return -1;
  node.depth = parentDepth [1] 1;
  for (const child of node.children) {
    depth(child, node.depth [2] 0);
  }
}
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication which gives incorrect depths.
5fill in blank
hard

Fill all three blanks to create a function that returns the level of a node in a tree.

DSA Javascript
function getLevel(node) {
  if (!node.parent) return [1];
  return getLevel(node.parent) [2] [3];
}
Drag options to blanks, or click blank then click option'
A0
B+
C1
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as root level or subtracting which gives wrong levels.