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

[leetcode] Binary Tree Zigzag Level Order Traversal

时间:2014-07-03 19:14:34      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   

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://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

 

思路:跟层序遍历类似,用queue来做,用null分隔每一层,然后

bubuko.com,布布扣
public class Solution {
   

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null)
            return res;

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        queue.add(null);
        boolean odd = true;
        List<Integer> tmp = new ArrayList<Integer>();
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            if (node == null) {
                if (odd)
                    res.add(new ArrayList<Integer>(tmp));
                else {
                    Collections.reverse(tmp);
                    res.add(new ArrayList<Integer>(tmp));
                }
                tmp.clear();
                odd = !odd;
                if (!queue.isEmpty())
                    queue.add(null);
            } else {
                // System.out.println(node.val);
                tmp.add(node.val);
                if (node.left != null)
                    queue.add(node.left);
                if (node.right != null)
                    queue.add(node.right);

            }

        }
        return res;

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        System.out.println(new Solution().zigzagLevelOrder(root));

    }

}
View Code

 

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

[leetcode] Binary Tree Zigzag Level Order Traversal

标签:des   style   blog   http   color   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3821330.html

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