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

按之字形顺序打印二叉树

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
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        Stack<TreeNode> stack = new Stack<>();
        Deque<TreeNode> container = new LinkedList<>();
        boolean direction = false;

        ArrayList<Integer> list = new ArrayList<>();
        if(pRoot != null){
            stack.add(pRoot);
            list.add(pRoot.val);
            res.add(list);
        }
        while(!stack.isEmpty() || !container.isEmpty()){
            if(stack.isEmpty() && !container.isEmpty()){
                list = new ArrayList<Integer>();
                direction = !direction;
                while(!container.isEmpty()){
                    TreeNode temp = container.poll();
                    stack.add(temp);
                    list.add(temp.val);
                }
                res.add(list);
            } else {
                TreeNode node = stack.pop();
                if(direction){
                    if(node.left != null){
                        container.add(node.left);
                    }
                    if(node.right != null){
                        container.add(node.right);
                    }
                } else {
                    if(node.right != null){
                        container.add(node.right);
                    }
                    if(node.left != null){
                        container.add(node.left);
                    }
                }
            }
        }
        return res;
    }
}

全部评论

相关推荐

04-17 10:16
门头沟学院 Java
小浪_coder:24届很难找了,马上25的都毕业了还有很多没找到的
点赞 评论 收藏
分享
05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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