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

题意:按照Zigzag这种方式层序遍历二叉树

解决思路:通过题目要求我们可以知道,当前遍历层数为基数的时候,遍历的方式是从左到右;反之从右到左。那么我们在遍历的过程只要根据当前层数决定遍历元素的进入存储结构的插入方式就可以了,从左往右则正常插入;反之则逆序插入。其他的就是正常的层序遍历

代码:

public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        travel(result, root, 0);
        return result;
    }

    private void travel(List<List<Integer>> result, TreeNode root, int level){
        if(root == null){
            return;
        }

        if(result.size() <= level){
            List<Integer> next = new LinkedList<>();
            result.add(next);
        }

        List<Integer> temp = result.get(level);
        if(level % 2 == 0){
            temp.add(root.val);
        } else{
            temp.add(0, root.val);
        }

        travel(result, root.left, level + 1);
        travel(result, root.right, level + 1);
    }
}

你可能感兴趣的:(LeetCode)