java - Trying to print top view of a tree using two if statements -
problem statement
you given pointer root of binary tree. print top view of binary tree. have complete function.
my code:
void top_view(node root) { node r = root; if(r.left!=null){ top_view(r.left); system.out.print(r.data + " "); } if(r.right!=null){ system.out.print(r.data + " "); top_view(r.right); } } the 2 if statements executed every time function called, need 1 of them execute. tried switch giving constant expression error. have found different solution problem.
so want know if can make 1 if execute @ time i.e, there way fix code without changing approach?

problem link: https://www.hackerrank.com/challenges/tree-top-view
this problem can solved using:
stack: print root , left subtree.
queue: print right subtree.
your function should this:
void topview(node root) { if(root==null) return; stack<integer> s=new stack<integer>(); s.push(root.data); node root2=root; while(root.left!=null) { s.push(root.left.data); root=root.left; } while(s.size()!=0) system.out.print(s.pop()+" "); queue<integer> q=new linkedlist<integer>(); q.add(root2.right.data); root2=root2.right; while(root2.right!=null) { q.add(root2.right.data); root2=root2.right; } while(q.size()!=0) system.out.print(q.poll()+" "); }
Comments
Post a Comment