码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode-103(Java) Binary Tree Zigzag Level Order Traversal

时间:2015-08-05 10:04:33      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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

传送门:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = new LinkedList<List<Integer>>();
        if(root == null)
            return lists;
        Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
        currentLevel.add(root);
        int cnt = 0;
        while(!currentLevel.isEmpty())
        {
            int size = currentLevel.size();    
            List<Integer> list = new LinkedList<Integer>();
            for(int i = 0; i < size; i ++)
            {
                TreeNode currentNode = new TreeNode(0);
                currentNode = currentLevel.poll();
                list.add(currentNode.val);
                if(currentNode.left != null)
                    currentLevel.add(currentNode.left);
                if(currentNode.right != null)
                    currentLevel.add(currentNode.right);        
            }
            if(cnt % 2 == 1)
                Collections.reverse(list);
            ++ cnt;
            lists.add(list);
        }
        return lists;
    }
}

 

Leetcode-103(Java) Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/zetrov/p/4703834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!