To prove safety offer 59. zigzag binary tree print order

Title Description

Implement according to a zigzag print function binary tree, i.e., left to right, the first print line of the second layer in order to print from right to left, the third line from left to right order of printing, in other rows forth.
 

Problem-solving ideas

S1 with a stack to store the odd-layer node, the other to hold the even-layer stack node s2
 

code show as below

public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        
             int layer = 1;
             //s1存奇数层节点
             Stack<TreeNode> s1 = new Stack<TreeNode>();
             s1.push(pRoot);
             //s2存偶数层节点
             Stack<TreeNode> s2 = new Stack<TreeNode>();
              
             ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
              
             while (!s1.empty() || !s2.empty()) {
                 if (layer%2 != 0) {
                     ArrayList<Integer> temp = new ArrayList<Integer>();
                     while (!s1.empty()) {
                         TreeNode node = s1.pop();
                         if(node != null) {
                             temp.add(node.val);
                             System.out.print(node.val + " ");
                             s2.push(node.left);
                             s2.push(node.right);
                         }
                     }
                     if (!temp.isEmpty()) {
                         list.add(temp);
                         layer++;
                         System.out.println();
                     }
                 } else {
                     ArrayList<Integer> temp = new ArrayList<Integer>();
                     while (!s2.empty()) {
                         TreeNode node = s2.pop();
                         if(node != null) {
                             temp.add(node.val);
                             System.out.print(node.val + " ");
                             s1.push(node.right);
                             s1.push(node.left);
                         }
                     }
                     if (!temp.isEmpty()) {
                         list.add(temp);
                         layer++;
                         System.out.println();
                     }
                 }
             }
             return list;

        }

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11416643.html