1 ms Java easy recursive solution


  • 1
    L
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root != null) {
                levelOrderR(root, 0, result);
            }
            return result;
        }
    
        public void levelOrderR(TreeNode p, int level, List<List<Integer>> result) {
            if (p == null) {
                return;
            }
            ArrayList<Integer> current;
            if (level >= result.size()) {
                current = new ArrayList<>();
                result.add(current);
            } else {
                current = (ArrayList<Integer>) result.get(level);
            }
            current.add(p.val);
            levelOrderR(p.left, level + 1, result);
            levelOrderR(p.right, level + 1, result);
        }
    }

Log in to reply
 

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