Very Simple JAVA Solution


  • 0
    W
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            dfs(root, 0, result);
            return result;
        }
        
        public void dfs(TreeNode root, int depth, List<List<Integer>> result){
            if(root==null) return;
            if(depth>=result.size()){
                List<Integer> list = new LinkedList<Integer>();
                list.add(root.val);
                result.add(list);
            } 
            else{
                result.get(depth).add(root.val);
            }
            dfs(root.left, depth+1, result);
            dfs(root.right, depth+1, result);
        }
    }
    

Log in to reply
 

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