Easy to understand JAVA solution- With explanation (4 ms)


  • 0
    T

    So idea is to pass all the nodes on a level, parse them and keep adding their children for next traversal.
    Start with root and do it recursively until no children found on the next level.

    public class Solution {
        List<List<Integer>> ans = new LinkedList();
        public List<List<Integer>> levelOrder(TreeNode root) {
            if(root==null)return ans;
            List<TreeNode> next_level = new ArrayList();
            next_level.add(root);
            levelOrder(next_level);
            return ans;
        }
        void levelOrder(List<TreeNode> level){
            if(level.size()==0)return ;
            List<TreeNode> next_level = new ArrayList();
            List<Integer> temp = new ArrayList();
            for(TreeNode t : level){
                    temp.add(t.val);
                    if(t.left!=null)next_level.add(t.left);
                    if(t.right!=null)next_level.add(t.right);
            }
            ans.add(temp);
            levelOrder(next_level);
        }
        
    }
    

Log in to reply
 

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