zoukankan      html  css  js  c++  java
  • 剑指 Offer 32

    /**
     * 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;
        }
    }
  • 相关阅读:
    430flash的操作
    430单片机之定时器A功能的大致介绍
    MSP430看门狗
    430之通用异步串口通信模块
    430的启动,I/O中断
    Msp430概述
    烦躁
    12864密码锁
    单片机的动手实践篇--51单片机玩转12864
    【CSS】font样式简写(转)- 不是很建议简写
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14138972.html
Copyright © 2011-2022 走看看