0
0
DSA Javascriptprogramming~20 mins

Height of Binary Tree in DSA Javascript - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Height Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the height of this binary tree?
Consider the following binary tree structure and code to calculate its height. What is the output printed by the code?
DSA Javascript
class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

function height(root) {
  if (!root) return 0;
  const leftHeight = height(root.left);
  const rightHeight = height(root.right);
  return Math.max(leftHeight, rightHeight) + 1;
}

const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

console.log(height(root));
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Think about the longest path from the root to a leaf node.
Predict Output
intermediate
2:00remaining
Output of height function on a skewed tree
What will be the output of the height function when called on this skewed binary tree?
DSA Javascript
class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

function height(root) {
  if (!root) return 0;
  return Math.max(height(root.left), height(root.right)) + 1;
}

const root = new Node(10);
root.right = new Node(20);
root.right.right = new Node(30);
root.right.right.right = new Node(40);

console.log(height(root));
A0
B3
C1
D4
Attempts:
2 left
💡 Hint
Count the nodes along the right side.
🔧 Debug
advanced
2:00remaining
Identify the error in height calculation
The following code is intended to calculate the height of a binary tree. What error will it produce when run?
DSA Javascript
function height(root) {
  if (root == null) {
    return -1;
  }
  const leftHeight = height(root.left);
  const rightHeight = height(root.right);
  return Math.max(leftHeight, rightHeight);
}

const root = { value: 1, left: null, right: null };
console.log(height(root));
A0
BTypeError
C-1
DInfinity
Attempts:
2 left
💡 Hint
Check the base case and the return statement.
🧠 Conceptual
advanced
1:00remaining
Height of an empty tree
What is the height of an empty binary tree (null root)?
A0
B-1
C1
Dundefined
Attempts:
2 left
💡 Hint
Think about how height is defined for no nodes.
🚀 Application
expert
3:00remaining
Calculate height after inserting nodes
Given an initially empty binary tree, nodes are inserted in this order: 5, 3, 8, 1, 4, 7, 9. What is the height of the tree after all insertions?
A4
B3
C2
D5
Attempts:
2 left
💡 Hint
Visualize the tree structure after inserting nodes in given order.