2ms recursive clean Java Solution without Stack or Queues


  • 1
    C
    public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if(root != null){
            List<Integer> subList = new ArrayList<Integer>();
            List<TreeNode> nodeList = new ArrayList<TreeNode>();
            subList.add(root.val);
            nodeList.add(root);
            result.add(subList);
            traverseLevel(nodeList, result);
        }
        
        return result;
    }
    
    public void traverseLevel(List<TreeNode> nodeList, List<List<Integer>> resultList){
            List<TreeNode> newNodeList = new ArrayList<TreeNode>();
            List<Integer> subList = new ArrayList<Integer>();
            for(int i = 0; i < nodeList.size(); i++){
                TreeNode parent = nodeList.get(i);
                if(parent.left != null){
                    subList.add(parent.left.val);
                    newNodeList.add(parent.left);
                }
            
                if(parent.right != null){
                    subList.add(parent.right.val);
                    newNodeList.add(parent.right);
                }
            }
            if(subList.size() > 0){
                resultList.add(subList);    
                traverseLevel(newNodeList, resultList);
            }
    }
    

    }


  • 0
    W

    Nice recursion, but this problem is bottom-up level order traversal.


Log in to reply
 

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