首页 > 其他 > 详细

Binary Tree Zigzag Level Order Traversal

时间:2014-06-08 17:28:02      阅读:264      评论: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]
]

方法

对树进行层次遍历,然后将奇数行得到的结果进行反转。
    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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!