Middle-题目70:103. 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]
]
题目大意:
给出一个二叉树,求锯齿形遍历结果。
题目分析:
其实还是基于层次遍历的,在Easy-题目27基础上加入一个flag,记录该行是应该正向还是应该反向就好了。
源码:(language:java)

/**
 * 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) {
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        Queue<Integer> levelqueue=new LinkedList<Integer>();

        queue.add(root);
        levelqueue.add(1);
        boolean isReverse = true;
        List<List<Integer>> result=new ArrayList();
        List<Integer> temp=new ArrayList<Integer>();
//      temp.add(root.val);
//      result.add(temp);
        if(root==null)
            return result;
        while(!queue.isEmpty())
        {
            TreeNode current=queue.remove();
            int curLevel=levelqueue.remove();
            //System.out.println(current.val+" level="+curLevel);

            if(curLevel==result.size())
            {
                temp.add(current.val);
            }
            else
            {
                if(isReverse)
                    Collections.reverse(temp);
                result.add(temp);               
                isReverse = !isReverse;
                temp=new ArrayList<Integer>();
                temp.add(current.val);  
            }
            if(current.left!=null)
            {
                queue.add(current.left);
                levelqueue.add(curLevel+1);
            }
            if(current.right!=null)
            {
                queue.add(current.right);
                levelqueue.add(curLevel+1);
            }
        }
        if(isReverse)
            Collections.reverse(temp);
        result.add(temp);
        result.remove(0);
    //  Collections.reverse(result);
        return result;        
    }
}

成绩:
4ms,beats 4.14%,众数3ms,45.49%

阅读更多
版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs https://blog.csdn.net/cmershen/article/details/51547036
个人分类: Leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Middle-题目70:103. Binary Tree Zigzag Level Order Traversal

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭