Offer to prove safety fifty-nine: zigzag print order binary tree

Casual working

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.

Thinking

First, think about this for a binary tree traversal, and is a sequence traversal (needless to say I think the Ah)
but for the purposes of traversal sequence from left to right are, how we implement traversal sequence, using the queue implementation , each layer placed in a queue to be inside out, and now we want to achieve the shape, not that the judgment in a special line, first put in a stack inside, and then taken out when it will reverse the duck. Is a simple deformation sequence traversal, personally feel tree to the test in the interview quite a number of basic traversal must be thoroughly cooked and heart, just like sorting algorithm, later a part of the algorithm of ordering.

Code

  public ArrayList<ArrayList<Integer>> Print(TreeNode root) {
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        Stack<Integer> stack=new Stack<Integer>();
         ArrayList<ArrayList<Integer>> arrays=new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> array=new ArrayList<Integer>();
        int j=1;
        if(root==null)return arrays;
        queue.offer(root);
       // array.add(root.val); 如何进行表示表示他们是在同一层 是个问题的关键所在 这一点想不出来啊有点 可以利用for循环来实现
           
        while(queue.size()!=0){
            int len=queue.size();
            for(int i=0;i<len;i++){
                 TreeNode temp=queue.poll();
            if(temp.left!=null){
                queue.add(temp.left);
            }
            if(temp.right!=null){
                queue.add(temp.right);
            }
                if(j%2==0){
                    stack.push(temp.val);
                    if(i==len-1){
                        while(!stack.isEmpty()){
                            int p=stack.pop();
                            array.add(p);
                        }
                    }
                }
                else{
                     array.add(temp.val);
                }
            }
            j++;
            arrays.add(array);
             array=new ArrayList<Integer>();
        }
        return arrays;
    }
Published 84 original articles · won praise 53 · views 7385

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105422372