Java Solution using 2 ArrayList


  • 0
    D

    Below is the iterative java solution using 2 ArrayList

    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> results = new ArrayList<List<Integer>>();
            ArrayList<TreeNode> temp1 = new ArrayList<TreeNode>();
            ArrayList<TreeNode> temp2;
            TreeNode tempNode;
            if(root != null){
                temp1.add(root);
                while(temp1.size()>0){
                    ArrayList<Integer> list = new ArrayList<Integer>();
                    temp2 = new ArrayList<TreeNode>();
                    for(int i = 0; i<temp1.size(); i++) {
                        tempNode = temp1.get(i);
                        list.add(tempNode.val);
                        if(tempNode.left!=null) temp2.add(tempNode.left);
                        if(tempNode.right!=null) temp2.add(tempNode.right);
                    }
                    temp1 = temp2;
                    results.add(list);
                }
            }
            return results;
        }
    }

Log in to reply
 

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