Prove safety offer: zigzag print binary tree (Stack | two-way queue + preorder)

1. Title Description

/ ** 
    Please implement a function in accordance with the binary print zigzag, 

    i.e., the first print line order from left to right, 
    the second layer is printed in the order from right to left, 
    the third row from left to right printing order, 
    other lines and so on. 
* /

2. The two-way queue

/ * Idea: to achieve a doubly linked list of features is the use of the underlying LinkedList in Java. 
  1) queue can be used to realize the hierarchical tree traversal 
  2) can traverse bidirectional, odd traverse back layer front, back to front traverse from the even layers 
* /

3. Code (+ levels doubly linked list traversal)

import java.util.*;

public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        return levelorder(pRoot);
    }
     public static ArrayList<ArrayList<Integer>> levelorder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(root == null) return result;
        queue.offer(root); //First, the enqueue root root 
        int Level = 0; // recording layers of 
        the while (! Queue.isEmpty ()) { // Queue is not empty, the cycle 
            the LinkedList <Integer> = Node new new the LinkedList <> (); // the stored value for each layer node 
            int length = queue.size (); // for each layer node number of 
            the while (length> 0 ) { 
                the TreeNode Tree = queue.poll ();
                 IF (! tree.left = null ) { 
                    Queue.offer (tree.left); 
                } 
                IF (tree.right =! null  ) {
                    Queue.offer (tree.right);
                } 
                IF ((+ Level. 1)% 2 == 0 ) { 
                    node.addFirst (tree.val); 
                } the else { 
                    node.add (tree.val); 
                } 
                
                length - ; 
            } 
            
            // Node layer through the results of the present
             // the linkedlist converted into the ArrayList 
            the ArrayList <Integer> = arrayNode new new the ArrayList <> ();
             for (Integer I: Node) { 
                arrayNode.add (I); 
            } 
            result.add (arrayNode); 
            // after the cycle, to give the Queue to prepare for the next layer,
            level++;
        }
        return result;
    }
}

 

Guess you like

Origin www.cnblogs.com/haimishasha/p/11520969.html