Java preorder traversal, also a fundamental template solution.


  • 0
    Z

    pretty straightforward.

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            traverse(root, res, 0);
            return res;
        }
        
        private void traverse(TreeNode root, List<List<Integer>> res, int level) {
            if (root == null) return;
            if (res.size() - 1 < level) {
                res.add(new ArrayList<>());
            }
        
            res.get(level).add(root.val);
            
            level++;
            traverse(root.left, res, level);
            traverse(root.right, res, level);
            
        }
    }
    

Log in to reply
 

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