MY DFS SOLUTION


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

Log in to reply
 

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