按照之字形打印二叉树

按照之字形打印二叉树

描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

Solution

public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<Integer> floor = new ArrayList<>();
        int index=0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        floor.add(1);
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
        while(!queue.isEmpty()){
            floor.add(0);
            ArrayList<Integer> arrayList = new ArrayList<>();
            for(int i=0;i<floor.get(index);i++) {
                TreeNode top = queue.poll();
                if (top != null) {
                    arrayList.add(top.val);
                    queue.offer(top.left);
                    queue.offer(top.right);
                    floor.set(index+1,floor.get(index+1)+2);
                }
            }
            if(arrayList.size()!=0){
                if ((index & 1) == 1) Collections.reverse(arrayList);
                arrayLists.add(arrayList);
            }
            index++;
        }
        return arrayLists;
    }
}

猜你喜欢

转载自blog.csdn.net/foradawn/article/details/80290120
今日推荐