码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Zigzag Level Order Traversal

时间:2014-06-08 17:29:07      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:leetcode      层次遍历   java   

题目

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 List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    	List<List<Integer>> list = new ArrayList<List<Integer>>();
    	
    	if (root == null) {
    		return list;
    	}
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
        	int len = queue.size();
        	List<Integer> subList = new ArrayList<Integer>();
        	for(int i = 0; i < len; i++) {
        		TreeNode curNode = queue.poll();
        		subList.add(curNode.val);
        		if (curNode.left != null) {
        			queue.offer(curNode.left);
        		}
        		if (curNode.right != null) {
        			queue.offer(curNode.right);
        		}
        	}
        	list.add(subList);
        }
    	int i = 0;
    	for (List<Integer> subList: list) {
    		if (i % 2 == 1) {
    			Collections.reverse(subList);
    		}
    		i++;
    	}
    	return list;
    }


Binary Tree Zigzag Level Order Traversal,布布扣,bubuko.com

Binary Tree Zigzag Level Order Traversal

标签:leetcode      层次遍历   java   

原文地址:http://blog.csdn.net/u010378705/article/details/28628219

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