DEV Community

Bvnkumar
Bvnkumar

Posted on

Print left view of binary tree

class Node{
  constructor(data,left,right){
    this.data=data;
    this.left=left;
    this.right=right;
  }
}

const tree=new Node(10);
tree.left=new Node(1)
tree.right=new Node(3)
tree.left.left=new Node(4)
tree.left.right=new Node(5)
tree.right.right=new Node(6)
tree.right.left=new Node(2);
tree.right.right.left=new Node(7)
tree.left.right.left=new Node(8)
tree.left.right.right=new Node(9)
tree.left.right.left.left=new Node(10);

let max_level=0;
function leftsideView(node,level){
  if(node==null){
    return null;
  }
  if(max_level<level){
    console.log(node.data)
    max_level=level;
  }
  leftsideView(node.left,level+1);
  leftsideView(node.right,level+1);
}
leftsideView(tree,1)
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
anumit profile image
ANUMIT JOOLOOR

Thank you very much for this post. I am studying binary trees to prepare for faang interviews.

Collapse
 
anumitjooloor profile image
anumit-jooloor

Thank you very much for this post. I have studying binary trees to prepare for faang interviews.