Java 2ms solution


  • 0
    T
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> myResult = new LinkedList<List<Integer>>(); 
            if(root == null) return myResult; 
            LinkedList<TreeNode> mylist = new LinkedList<TreeNode>(); 
            mylist.add(root); 
            int l = 1; 
            int s = 0; 
            while(!mylist.isEmpty()) {
                LinkedList<Integer> result = new LinkedList<Integer>(); 
                for(int i=0;i<l;i++) {
                    TreeNode node = mylist.remove(); 
                    result.add(node.val);
                    if(node.left !=null) {
                        s = s + 1; 
                        mylist.add(node.left);
                    }
                      if(node.right !=null) {
                        s = s + 1; 
                        mylist.add(node.right);
                    }
                }
                l = s; 
                s = 0; 
                myResult.add(result);
                
            }
            
            return myResult;
            
        }
    }

Log in to reply
 

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