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]
    ]
    

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer> > result = new ArrayList<List<Integer> >();
    		if(root != null){
    			Stack<TreeNode> topLevel = new Stack<TreeNode>();
    			topLevel.push(root);
    			int reverse = 1;
    			while(!topLevel.isEmpty()) {
    				Stack<TreeNode> nextLevel = new Stack<TreeNode>();
    				List<Integer> value = new ArrayList<Integer>();
    				while(!topLevel.isEmpty()) {
    					TreeNode node = topLevel.pop();
    					value.add(node.val);
    					if(reverse % 2 == 1){
    					    if(node.left != null)
    						    nextLevel.push(node.left);
    					    if(node.right != null)
    						    nextLevel.push(node.right);
    					}
    					else{
    					    if(node.right != null)
    						    nextLevel.push(node.right);
    					    if(node.left != null)
    						    nextLevel.push(node.left);
    					}
    				}
    				++reverse; 
    				result.add(value);
    				topLevel = nextLevel;
    			}
    		}
    		return result;    
        }
    }
    

      

  • 相关阅读:
    驱动
    设备编号
    makefile 中的赋值
    UART
    c 语言的复杂声明
    linux下arm汇编的常用指令解析
    linux下的arm汇编程序
    ok6410下的uboot分析与实现
    层级选择器的理解
    css外部样式的理解
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3769935.html
Copyright © 2011-2022 走看看