牛客《剑指Offer》按之字形顺序打印二叉树

题:https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=13&tqId=11212&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

使用两个栈,同时 每个栈 的 入栈策略不同,即 左右 子树 放入的 顺序不同。

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>> res = new ArrayList();
        if(pRoot == null)
            return res;
        Stack<TreeNode> stack1 = new Stack();
        Stack<TreeNode> stack2=  new Stack();
        stack1.push(pRoot);
        while(!stack1.isEmpty() || !stack2.isEmpty()){
            ArrayList<Integer> eRes = new ArrayList();
            if(!stack1.isEmpty()){
                while(!stack1.isEmpty()){
                    TreeNode curNode = stack1.pop();
                    eRes.add(curNode.val);
                    if(curNode.left != null)
                        stack2.push(curNode.left);
                    if(curNode.right !=null)
                        stack2.push(curNode.right);
                }
            }else{
                while(!stack2.isEmpty()){
                    TreeNode curNode = stack2.pop();
                    eRes.add(curNode.val);
                    if(curNode.right != null)
                        stack1.push(curNode.right);
                    if(curNode.left != null)
                        stack1.push(curNode.left);
                }
            }
            res.add(eRes);
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode)