leetcode-103 二叉树的锯齿形层次遍历 JAVA代码

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

[
  [3],
  [20,9],
  [15,7]
]

java代码

public List> zigzagLevelOrder(TreeNode root) {
        
        List> result = new LinkedList>();
        List temList = new LinkedList();
        if (root == null) {
            return result;
        }
        Queue queue = new LinkedList();
        ((LinkedList) queue).add(root);
        int num = 1;
        int next = 0;
        int flag = 0;
        while (!queue.isEmpty()) {
            TreeNode now = queue.poll();
            num--;
            if(result.size()%2==0){
                temList.add(now.val);

            }else {
                ((LinkedList) temList).addFirst(now.val);
            }
            if (now.left != null) {
                ((LinkedList) queue).add(now.left);
                next++;
            }
            if (now.right != null) {
                ((LinkedList) queue).add(now.right);
                next++;
            }
            if (num == 0) {
                num = next;
                next = 0;
                ((LinkedList>) result).add(temList);
                temList = new LinkedList();
            }
        }
        return result;
    
    }

你可能感兴趣的:(leetcode)