2ms Iterative solution implemented using ArrayList instead of queue


  • 0
    K

    The tree is traversed Breadth-Wise, making a temporary entry into the "tmpList". The for loop then iterates through each level of elements in the "tmpList" thus creating a list of node element for each level.

    public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> nodes= new ArrayList<List<Integer>>();
            if(root==null)  return nodes;
            List<TreeNode> tmpList = new ArrayList<TreeNode>();
            TreeNode tmpNode; int size;
            
            tmpList.add(root);
            while(!tmpList.isEmpty()){
                List<Integer> elem = new ArrayList<Integer>();
                size = tmpList.size();
                for(int i=0; i< size; i++){
                    tmpNode = tmpList.remove(0);
                    elem.add(tmpNode.val);
                    if(tmpNode.left!=null) tmpList.add(tmpNode.left);
                    if(tmpNode.right!=null) tmpList.add(tmpNode.right);    
                }
                nodes.add(elem);
            }
            return nodes;
        }

Log in to reply
 

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