Recursive DFS Java Solution [2ms]


  • 2
    R
    public class Solution {
        List<List<Integer>> result;
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            result = new ArrayList<List<Integer>>();
            if(root != null) zigzagLevelOrder(root, 0);
            return result;
        }
        
        public void zigzagLevelOrder(TreeNode root, int height) {
            if(root == null) return;
            if(height >= result.size()) result.add(new ArrayList<Integer>());
            
            if(height % 2 == 0) result.get(height).add(root.val);
            else result.get(height).add(0, root.val);
            
            zigzagLevelOrder(root.left, height+1);
            zigzagLevelOrder(root.right, height+1);
        }
    }

Log in to reply
 

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