[leetcode]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]
]

树按照一个“Z”字形进行遍历。

方法是采取递归得到正序的答案,再通过反置指定的队列完成。

得到正序答案采用的是递归过程,参照了我上一篇[leetcode]Binary Tree Level Order Traversal的代码。

实现如下:

public class Solution {
     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root != null) {
            levelOrderR(root, 0, result);
        }
        motify(result);
        return result;
    }

    public void levelOrderR(TreeNode treeNode, int level, List<List<Integer>> result) {
        if (treeNode == null) {
            return;
        }
        ArrayList<Integer> current;
        if (level >= result.size()) {
            current = new ArrayList<>();
            result.add(current);
        } else {
            current = (ArrayList<Integer>) result.get(level);
        }
        current.add(treeNode.val);
        levelOrderR(treeNode.left, level + 1, result);
        levelOrderR(treeNode.right, level + 1, result);
    }

    public void motify(List<List<Integer>> result) {
        for(int i = 0; i < result.size(); i++){
            if(i % 2 != 0){
                List<Integer> tmp = result.get(i);
                Collections.reverse(tmp);    // 队列元素转置
                result.set(i, tmp);
            }
        }
    }
}

虽然实现起来是有点丑陋,但是从运行的结果上来看效果还是可以的。

题目链接:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

你可能感兴趣的:(LeetCode)