We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Use either Iterative or Recursive method to swap nodes:
importjava.io.*;importjava.util.*;importjava.text.*;importjava.math.*;importjava.util.regex.*;classNode{intdata;intdepth;Nodeleft,right;Node(intdata,intdepth){this.data=data;this.depth=depth;}}publicclassSolution{publicstaticvoidswap_nodes(Noderoot,intK){/*Queue<Node> nodes = new LinkedList<Node>(); nodes.offer(root); Node cur; while (!nodes.isEmpty()){ cur = nodes.poll(); if (cur.depth%K == 0){ Node tmp = cur.left; cur.left = cur.right; cur.right = tmp; } if (cur.left != null) nodes.offer(cur.left); if (cur.right != null) nodes.offer(cur.right); }*/if(root!=null){if(root.depth%K==0){Nodetmp=root.left;root.left=root.right;root.right=tmp;}swap_nodes(root.left,K);swap_nodes(root.right,K);}}publicstaticvoidinorder_print(Noderoot){if(root!=null){inorder_print(root.left);System.out.print(root.data+" ");inorder_print(root.right);}}publicstaticvoidprint_nodes(Noderoot,intK){swap_nodes(root,K);inorder_print(root);System.out.println();}publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannersc=newScanner(System.in);intN=sc.nextInt();Noderoot=newNode(1,1);Nodecur=root;Queue<Node>nodes=newLinkedList<Node>();nodes.offer(cur);while(N-->0){cur=nodes.poll();intleftData=sc.nextInt();intrightData=sc.nextInt();cur.left=(leftData==-1)?null:newNode(leftData,cur.depth+1);cur.right=(rightData==-1)?null:newNode(rightData,cur.depth+1);if(cur.left!=null&&cur.left.data!=-1)nodes.offer(cur.left);if(cur.right!=null&&cur.right.data!=-1)nodes.offer(cur.right);}intT=sc.nextInt();while(T-->0){intK=sc.nextInt();print_nodes(root,K);}}}
Swap Nodes [Algo]
You are viewing a single comment's thread. Return to all comments →
Use either Iterative or Recursive method to swap nodes: