按照广度优先搜索套路,判断反向| #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

import java.util.*;

/*
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) {
            Deque<TreeNode> queue = new LinkedList<>();
            queue.offer(pRoot);
            ArrayList<Integer> list = new ArrayList<>();
            list.add(pRoot.val);
            res.add(list);
            boolean leftOrder = false;
            while (!queue.isEmpty()) {
                int size = queue.size();
                ArrayList<Integer> temp = new ArrayList<>();
                while (size > 0) {
                    TreeNode poll = queue.poll();
                    if (poll.left != null) {
                        queue.offer(poll.left);
                        temp.add(poll.left.val);
                    }
                    if (poll.right != null) {
                        queue.offer(poll.right);
                        temp.add(poll.right.val);
                    }
                    size--;
                }
                if (temp.size()==0) {
                    break;
                }
                if (!leftOrder) {
                    Collections.reverse(temp);
                }
                res.add(temp);
                leftOrder = !leftOrder;
            }
        }
        return res;
    }

}

全部评论

相关推荐

10-25 12:05
已编辑
湖南科技大学 Java
若梦难了:我有你这简历,已经大厂乱杀了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务