Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, January 3, 2018

Diagonal Sum of Tree


Idea is to use 2 Queue

Code:

 public void diagonalsum(Node root)
     {
      Queue<Node> q1=new LinkedList<Node>();
      Queue<Node> q2=new LinkedList<Node>();
  boolean flag=true;
  q1.add(root);
  while(!q1.isEmpty() || !q2.isEmpty())
  {
  int c=0;
  if(flag)
  {
  while(!q1.isEmpty())
{
  Node temp=q1.poll();
  while(temp!=null)
  {
  c+=temp.data;
  if(temp.left!=null)
  q2.add(temp.left);
  temp=temp.right;
}}
  System.out.print(c+" ");
  }
  else {
while(!q2.isEmpty())
{
Node temp=q2.poll();
  while(temp!=null)
  {
  c+=temp.data;
  if(temp.left!=null)
  q1.add(temp.left);
  temp=temp.right;
  }}
  System.out.print(c+" ");
  }
  flag=!flag;
  }

0 Comments:

Post a Comment

Stats