print left view of binary tree in javascript

To print the left view of a binary tree, we need to traverse the tree in a way that we only print the leftmost node of each level. One way to achieve this is by using a recursive DFS (Depth First Search) algorithm.

Here's a JavaScript function that implements the left view of a binary tree:

index.tsx
class Node {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function printLeftView(root) {
  const result = [];
  if (!root) {
    return result;
  }

  function dfs(node, level) {
    if (node === null) {
      return;
    }
    if (level === result.length) {
      result.push(node.val);
    }
    dfs(node.left, level + 1);
    dfs(node.right, level + 1);
  }

  dfs(root, 0);

  return result;
}
446 chars
30 lines

In this function, we first create a Node class to represent each node in the binary tree. Then we declare the printLeftView function that takes in the root of the binary tree.

We initialize an empty array called result that will store the left view of the binary tree. If the root is null, we simply return result.

Then we declare a recursive function called dfs that takes in the node and the level of the current node.

In the dfs function, we first check if the node is null. If it is, we simply return.

If the current level is equal to the length of the result array, then it means we have reached a new level in the binary tree, so we push the value of the current node to the result array.

Then we make a recursive call to the dfs function for the left and right child nodes of the current node, incrementing the level by 1 each time.

Finally, we call the dfs function on the root node, passing in 0 as the initial level.

The result array now contains the left view of the binary tree, so we return it as the output of the printLeftView function.

Here's an example usage of the function:

index.tsx
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.left.right = new Node(8);
root.right.right = new Node(6);
root.right.right.left = new Node(7);

console.log(printLeftView(root)); // [1, 2, 4, 8]
296 chars
11 lines

This should output [1, 2, 4, 8], which is the left view of the binary tree.

gistlibby LogSnag