Easy to understand Java solution (2ms)


  • 0
    T
    public class Solution {
        List<List<Integer>> ans = new LinkedList();
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
                if(root==null)return ans;
                List<TreeNode> t = new ArrayList();
                t.add(root);
                levelOrder(t,false);
                return ans;
        }
        
        void levelOrder(List<TreeNode> level, boolean order) {
            if(level.size()==0)return;
            List<TreeNode> next_level = new ArrayList();
            List<Integer> temp = new ArrayList();
            
            for(TreeNode t : level){
                temp.add(t.val);
                if(t.left!=null)next_level.add(t.left);
                if(t.right!=null)next_level.add(t.right);
            }
            if(order)Collections.reverse(temp);
            ans.add(temp);
            levelOrder(next_level,!order);
        }
    }
    

Log in to reply
 

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