美文网首页
103. Binary Tree Zigzag Level Or

103. Binary Tree Zigzag Level Or

作者: 7ccc099f4608 | 来源:发表于2020-03-15 23:51 被阅读0次

    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<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if(root == null) {
                return res;
            }
    
            helper(root, res, 0);
    
            return res;
        }
    
        private void helper(TreeNode root, List<List<Integer>> res, int level) {
    
            if(root == null) {
                return ;
            }
    
            if(level >= res.size()) {
                res.add(new LinkedList<>());  // add(0,xxx)操作性能更优
            }
    
            List<Integer> 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 Or

          本文链接:https://www.haomeiwen.com/subject/zsniehtx.html