Fast DFS JAVA solution very easy to understand


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

Log in to reply
 

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