103. Binary Tree Zigzag Level Order Traversal

https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/

image.png

(图片来源https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/

日期 是否一次通过 comment
2020-03-15 0

递归

public List> zigzagLevelOrder(TreeNode root) {
        List> res = new ArrayList<>();
        if(root == null) {
            return res;
        }

        helper(root, res, 0);

        return res;
    }

    private void helper(TreeNode root, List> res, int level) {

        if(root == null) {
            return ;
        }

        if(level >= res.size()) {
            res.add(new LinkedList<>());  // add(0,xxx)操作性能更优
        }

        List temp = res.get(level);
        if((level & 1) == 0) {
            temp.add(root.val);
        } else {
            temp.add(0, root.val);
        }

        helper(root.left, res, level+1);
        helper(root.right, res, level+1);
    }

你可能感兴趣的:(103. Binary Tree Zigzag Level Order Traversal)