To prove safety: zigzag print binary tree

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.

Such as a binary tree:

            1
    	   /  \
    	  2    3
    	 / \   / \
    	4  5   6  7

Print results:

1
3 2
4 5 6 7


solution

Zigzag print, that is, first from left to right , the right to left , with the stack structure to achieve;

Two auxiliary stack: storing a stack of odd-layer node S1 , an even layer stack storage node S2 .

s1 pop stack node, its node left -> right child s2 into the stack;

s2 stack pop node, its node right -> left child s1 into the stack;

The order is the order of the stack of print.

import java.util.ArrayList;
import java.util.Stack;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if(pRoot==null){
            return res;
        }
        
        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();
        
        s1.push(pRoot);
        int layer = 1;
        
        while(!s1.isEmpty() || !s2.isEmpty()){
            
            if(layer%2 != 0){ //奇数层
                ArrayList<Integer> list = new ArrayList<>();
                while(!s1.isEmpty()){
                    TreeNode node = s1.pop();
                    if(node != null){
                        list.add(node.val); //
                        s2.push(node.left);
                        s2.push(node.right);
                    }
                }
                if(!list.isEmpty()){
                    res.add(list);
                    layer++;
                }
            }else{//偶数层
                ArrayList<Integer> list = new ArrayList<>();
                while(!s2.isEmpty()){
                    TreeNode node = s2.pop();
                    if(node != null){
                        list.add(node.val); //
                        s1.push(node.right);
                        s1.push(node.left);
                    }
                }
                if(!list.isEmpty()){
                    res.add(list);
                    layer++;
                }
            }
        }
            
        return res;
    }
}

 

 

 











Guess you like

Origin www.cnblogs.com/lisen10/p/11559930.html