算法题:按之字形打印二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010221508/article/details/88606012

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推

import java.util.ArrayList;
import java.util.Stack;
/*
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) {
        ArrayList<ArrayList<Integer>> list = new ArrayList();
        if(pRoot == null) {
            return list;
        }
        Stack<TreeNode> stack1 = new Stack();
        Stack<TreeNode> stack2 = new Stack();
        stack1.push(pRoot);
        while(!stack1.isEmpty() || !stack2.isEmpty()) {
            ArrayList<Integer> layer = new ArrayList();
            if(!stack1.isEmpty()) {
                while(!stack1.isEmpty()) {
                    TreeNode root = stack1.pop();
                    layer.add(root.val);
                    if(root.left != null) stack2.push(root.left);
                    if(root.right != null) stack2.push(root.right);
                }
            }else if(!stack2.isEmpty()) {
                while(!stack2.isEmpty()) {
                    TreeNode root = stack2.pop();
                    layer.add(root.val);
                    if(root.right != null) stack1.push(root.right);
                    if(root.left != null) stack1.push(root.left);
                }
            }
            list.add(layer);
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/u010221508/article/details/88606012