剑指 Offer 32 - III. 从上到下打印二叉树 III

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        //用2个栈实现,奇栈从左往右排,偶栈从右往左排
        Stack<TreeNode> stackJi = new Stack<>();
        Stack<TreeNode> stackOu = new Stack<>();
        //判空
        if(root == null) return res;
        //二叉树第一册为根节点,入奇数栈
        stackJi.push(root);
        int flag = 0;     //标志位,1,3,入奇栈,2,4入偶栈
        while(!stackJi.isEmpty() || !stackOu.isEmpty() ){
            List<Integer> tmp = new LinkedList<>();
            //判定奇偶
            if(flag == 0){//
                while(!stackJi.isEmpty()){
                TreeNode node = stackJi.pop();
                tmp.add(node.val);

                if(node.left !=null){stackOu.push(node.left);}
                if(node.right!=null){stackOu.push(node.right);}
                }
            }
            //
            else{
                while(!stackOu.isEmpty()){
                TreeNode node = stackOu.pop();
                tmp.add(node.val);

                if(node.right!=null){stackJi.push(node.right);}
                if(node.left !=null){stackJi.push(node.left);}
                
                }
            }         
            flag = (flag +1)%2; //标志位 交替
            res.add(tmp);   //存入本层结果
        }
        return res;
    }
}

 

posted @ 2020-12-15 15:30  peanut_zh  阅读(93)  评论(0编辑  收藏  举报