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

按之字形顺序打印二叉树

http://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 {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        if (pRoot == null) {
            return new ArrayList<>();
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.add(pRoot);

        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        boolean left2Right = true;
        while(!stack.isEmpty()) {
            Stack<TreeNode> temp = new Stack<>();
            ArrayList<Integer> values = new ArrayList<>();
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();
                values.add(node.val);
                if (!left2Right) {
                    if (node.right != null) {
                        temp.add(node.right);
                    }
                    if (node.left != null) {
                        temp.add(node.left);
                    }
                } else {
                    if (node.left != null) {
                        temp.add(node.left);
                    }
                    if (node.right != null) {
                        temp.add(node.right);
                    }
                }
            }
            stack = temp;
            if (!values.isEmpty()) {
                result.add(values);
            }
            left2Right = !left2Right;
        }
        return result;
    }
}
全部评论

相关推荐

06-01 21:50
已编辑
天津理工大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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