zoukankan      html  css  js  c++  java
  • 【LeetCode】Binary Tree Zigzag Level Order Traversal

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]
    运用栈的先进先出特点,并保证每层元素进栈的顺序是从左向右,或者从右向左
    public class Solution {
        public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
            ArrayList<Integer> ai = new ArrayList<Integer>();
            ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
            if(root==null)
                return re;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            Stack<TreeNode> tempStack = new Stack<TreeNode>();
            stack.push(root);
            int i=0;
            while(!stack.isEmpty()){
                TreeNode tempnode = stack.peek();
                stack.pop();
                ai.add(tempnode.val);
                //根据层序的层数来确定是从左向右添加还是从右向左添加
                //保证stack中的顺序是连续的
                if(i%2==0){
                    if(tempnode.left!=null){
                        tempStack.push(tempnode.left);
                    }
                    if(tempnode.right!=null){
                        tempStack.push(tempnode.right);
                    }
                }else{
                    if(tempnode.right!=null){
                        tempStack.push(tempnode.right);
                    }
                    if(tempnode.left!=null){
                        tempStack.push(tempnode.left);
                    }
                }
                
                if(stack.isEmpty()){
                    i++;
                    stack=tempStack;
                    
                    tempStack = new Stack<TreeNode>();
                    re.add(ai);
                    ai=new ArrayList<Integer>();
                }
                
            }
            return re;
            
        }
    }
  • 相关阅读:
    数据类型
    蓝牙Controller框架梳理
    蓝牙协议框架梳理
    低功耗蓝牙漏洞分析
    C语言进阶1-#define和const
    KMP算法详细分解
    C语言---指针变量详解3
    C语言---指针变量详解2
    C语言---指针变量详解1
    C语言---指针变量作为函数参数
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3722558.html
Copyright © 2011-2022 走看看