Simple Java recursive solution


  • 0
    I
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<TreeNode> generateTrees(int n) {
            
            if(n == 0) {
                return new ArrayList<TreeNode>();
            }
            
            return gen(1, n);
        }
        
        List<TreeNode> gen(int start, int end) {
            ArrayList<TreeNode> heads = new ArrayList<TreeNode>();
            if(start > end) {
                heads.add(null);
                return heads;
            }
            
            for(int i = start; i <= end; i++) {
                
                List<TreeNode> lefts = gen(start, i - 1);
                List<TreeNode> rights = gen(i + 1, end);
                
                for(TreeNode left : lefts) {
                    for(TreeNode right : rights) {
                        TreeNode head = new TreeNode(i);
                        head.left = left;
                        head.right = right;
                        heads.add(head);
                    }
                }
            }
            
            return heads;
            
        }
    }
    

Log in to reply
 

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