📖
Coding interview questions
  • 👋Coding Interview
  • Easy
    • Two number sum
    • Validate Subsequence
    • Sorted Squared Array
    • Tournament Winner
    • Non-Constructible Change
    • Find Closest Value in BTS
    • Branch sum
    • Node Depths
    • Depth-first Search
    • Minimum Waiting Time
    • Class Photos
  • Medium
    • Three Number Sum
    • Smallest Difference
    • Move Element To End
    • Monotonic Array
    • Spiral Traverse
    • Longest Peak
    • Array Of Products
    • First Duplicate Value
    • Merge Overlapping Intervals
    • Zero Sum Subarray
    • BST Traversal
    • Validate BST
    • Min Height BST
    • Find Kth Largest Value In BST
    • Reconstruct BST
    • Invert Binary Tree
  • Hard
    • Three Number Sum
  • Really-Hard
    • Three Number Sum
Powered by GitBook
On this page
  1. Easy

Node Depths

Node Depths

The distance between a node in a Binary Tree and the tree's root is called the node's depth.

Write a function that takes in a Binary Tree and returns the sum of its nodes' depths.

Each BinaryTree node has an integer value, a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null.

Sample Input

tree =    1
       /     \
      2       3
    /   \   /   \
   4     5 6     7
 /   \
8     9

Sample Output

16
// The depth of the node with value 2 is 1.
// The depth of the node with value 3 is 1.
// The depth of the node with value 4 is 2.
// The depth of the node with value 5 is 2.
// Etc..
// Summing all of these depths yields 16.
// O(n) time | O(h) space
function nodeDepths(root) {
  let sumOfDepths = 0;
  const stack = [{node: root, depth: 0}];
  while (stack.length > 0) {
    const {node, depth} = stack.pop();
    if (node === null) continue;
    sumOfDepths += depth;
    stack.push({node: node.left, depth: depth + 1});
    stack.push({node: node.right, depth: depth + 1});
  }
  return sumOfDepths
}

// This is the class of the input binary tree.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Do not edit the line below.
exports.nodeDepths = nodeDepths;
// O(n) time | O(h) space
function nodeDepths(root, depth = 0) {
  if(root === null) return 0
  return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1);
}

// This is the class of the input binary tree.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Do not edit the line below.
exports.nodeDepths = nodeDepths;
java

PreviousBranch sumNextDepth-first Search

Last updated 2 years ago

Page cover image