Find the deepest node in a binary tree.

To find the deepest node in a binary tree, we can use recursion. We can keep track of the maximum depth as we traverse the tree, and return the deepest node's value when we reach the end of the tree.

Problem

Given a binary tree, find the deepest node in the tree.
Example input:
    1
   / \
  2   3
     / \
    4   5
Example output:
5

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use a depth first search to traverse the tree.
// The depth first search will keep track of the current depth and the deepest node.
// The depth first search will return the deepest node.
// This solution is optimal because it only traverses the tree once.

function findDeepestNode(root) {
  let deepestNode = null;
  let deepestDepth = 0;

  function traverse(node, depth) {
    if (node === null) {
      return;
    }

    if (depth > deepestDepth) {
      deepestDepth = depth;
      deepestNode = node;
    }

    traverse(node.left, depth + 1);
    traverse(node.right, depth + 1);
  }

  traverse(root, 0);
  return deepestNode;
}

A.I. Evaluation of the Solution

This is a good solution that correctly finds the deepest node in a binary tree. The approach of using a depth first search is a good one, as it only needs to traverse the tree once. The code is well-written and easy to follow.

Evaluated at: 2022-12-12 00:15:28