2ms Iterative solution implemented using ArrayList instead of queue

  • 0

    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;
                List<Integer> elem = new ArrayList<Integer>();
                size = tmpList.size();
                for(int i=0; i< size; i++){
                    tmpNode = tmpList.remove(0);
                    if(tmpNode.left!=null) tmpList.add(tmpNode.left);
                    if(tmpNode.right!=null) tmpList.add(tmpNode.right);    
            return nodes;

Log in to reply

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