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.tsx446 chars30 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.tsx296 chars11 lines
This should output [1, 2, 4, 8]
, which is the left view of the binary tree.
gistlibby LogSnag