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

按之字形顺序打印二叉树

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
        ArrayList<ArrayList<Integer>> result = new ArrayList();
        // init: push pRoot
        Stack<TreeNode> stack = new Stack();
        if(pRoot != null) {
            stack.push(pRoot);
        }
        
        int count = 0;
        while (!stack.isEmpty()) {
            count++;
            ArrayList<TreeNode> list = new ArrayList();
            ArrayList<Integer> subResult = new ArrayList();
            while (!stack.isEmpty()) {
                TreeNode cur = stack.pop();
                list.add(cur);
                subResult.add(cur.val);
            }
            result.add(subResult);
            for (TreeNode cur : list) {
                if (count % 2 == 0) {
                    if (cur.right != null) {
                        stack.push(cur.right);
                    }
                    if (cur.left != null) {
                        stack.push(cur.left);
                    }
                } else {
                    if (cur.left != null) {
                        stack.push(cur.left);
                    }
                    if (cur.right != null) {
                        stack.push(cur.right);
                    }
                }

            }
        }
        return result;
        // while poll print, left right -> stack
        //       poll print, left right -> stack
    }
}

用一个栈来做翻转,每一层先把栈消费来print,同时暂存一个list;然后遍历list来读下一层,把下一层放入栈,注意奇数层是先left后right,偶数层就是先right后left

全部评论

相关推荐

点赞 评论 收藏
分享
Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务