1ms short java solution, using depth

  • 0

    We just need to set a flag indicating whether it should add elements from left to right or the opposite.

    public class Solution {
        // leftDirection = true means adding elements from left to right
        void dfs(TreeNode root, List<List<Integer>> result, int depth, boolean leftDirection) {
            if(root==null) return;
                result.add(new LinkedList<Integer>());
            List<Integer> cur = result.get(depth);
            if(!leftDirection) cur.add(0, root.val);
            else cur.add(root.val);
            dfs(root.left, result, depth+1, !leftDirection);
            dfs(root.right, result, depth+1, !leftDirection);
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            dfs(root, result, 0, true);
            return result;

Log in to reply

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