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

按之字形顺序打印二叉树

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

全部评论

相关推荐

26牛牛不会梦到感谢信:羡慕离职了还能吃吗现在就赶回去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务