题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

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 {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        // write code here
        if(pRoot==null){
            return new ArrayList<>();
        }
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        boolean isleft = true;
        ArrayDeque<TreeNode> q = new ArrayDeque<>();
        q.add(pRoot);
        while (!q.isEmpty()) {
            ArrayList<Integer>row = new ArrayList<>();
            int n = q.size();
            if (isleft) {
                for (int i = 0; i < n; i++) {
                    TreeNode cur = q.pollFirst();
                    row.add(cur.val);
                    //若是左右孩子存在,则存入左右孩子作为下一个层次
                    if (cur.left != null)
                        q.addLast(cur.left);
                    if (cur.right != null)
                        q.addLast(cur.right);
                }
                isleft = false;
            } else {
                for (int i = n-1; i >= 0; i--) {
                    TreeNode cur = q.pollLast();
                    row.add(cur.val);
                    if (cur.right != null)
                        q.addFirst(cur.right);
                    if (cur.left != null)
                        q.addFirst(cur.left);
                    
                }
                isleft = true;
            }
            res.add(row);

        }
        return res;
    }
}

这个也是不太擅长,我直接copy了第26题的代码,改了改。总之原理就是队列的进出方向改了,然后改吧改吧就行了。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务