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

按之字形顺序打印二叉树

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;
    }
}

全部评论

相关推荐

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