3ms Java solution without Queue


  • 0
    F
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root != null){
            result = new ArrayList<>();
            List<Integer> temp = null;
            List<TreeNode> children = new ArrayList<>();
            children.add(root);
            while (children != null && children.size() > 0){
                temp = new ArrayList<>();
                for (TreeNode item : children){
                    temp.add(item.val);
                }
                result.add(temp);
                children = getChildren(children);
            }
            Collections.reverse(result);
        }
        return result;
    }
    
    private List<TreeNode> getChildren(List<TreeNode> parents){
        List<TreeNode> res = null;
        if (parents != null && parents.size() > 0){
            res = new ArrayList<>();
            for (TreeNode item : parents){
                if (item.left != null) res.add(item.left);
                if (item.right != null) res.add(item.right);
            }
        }
        return res;
    }

Log in to reply
 

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