Share My DFS JAVA Solution; Beat 97%; easy to understand


  • 1
    H
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<List<Integer>>();
            helper(root,0,list);
            return list;
        }
        public void helper(TreeNode root, int level, List<List<Integer>> list){
            if (root==null) return;
            
            LinkedList<Integer> item;
            if(list.size()<=level) {
                item = new LinkedList<Integer>();
                list.add(item);
            }
            else item = (LinkedList)list.get(level);
            
            if(level%2==0)  item.add(root.val);
            else item.addFirst(root.val);
            
            helper(root.left,level+1,list);
            helper(root.right,level+1,list);
        }
    }

  • 0
    C

    Good! Seems like Cracking the coding Interview question 4.4.


Log in to reply
 

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