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;
        }
    }
  • 相关阅读:
    开通博客
    简单、方便、实用的日志记录系统
    浅谈近两年工作
    前端构建神器之 gulp
    CSS 3 transition属性
    angular.extend相关知识
    angular.element相关知识
    angularJS之$apply()方法
    Jquery选择器
    Jquery选择器小节
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14138972.html
Copyright © 2011-2022 走看看