Share my Java Solution(beat 87%)


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public void recursion(List<List<Integer>> ls, TreeNode root, int depth){
            if(root == null){
                return;
            }
            if(ls.size() > depth){
                ls.get(depth).add(root.val);
            }
            else{
                List<Integer> tmp = new ArrayList<Integer>();
                tmp.add(root.val);
                ls.add(tmp);
            }
            recursion(ls,root.left, depth+1);
            recursion(ls,root.right, depth+1);
        }
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> ans = new ArrayList<List<Integer>>();
            recursion(ans,root,0);
            for(int i = 0; i < ans.size(); i++){
                if(i % 2 == 1){
                    Collections.reverse(ans.get(i));
                }
            }
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.