Use DP to generate unique distinct binary trees;

Create to two integer value, one "start" to represent  the lowest value, and the other "end" to represent the highest value; The range of the whole true is from start to end, initially start = 1, end = n. 

Suppose i is the current root, then the left subtree value should be start - i-1, the right subtree value should be i+1 - end; Thus, we're going to check the different situation of of the range value. 

Case 1: if(start > end), this means invalid value range of left subtree, thus the left subtree should be null, add null to the list.

Case 2: if(start == end), this exactly points to one node, add the node to the list.

Case 3: The left situation is end > start, we can use a loop to set every node of value from start to end, as the root node, and recursively call this method to get the left subtree list and the right subtree list, then traverse each list to get all the possible combination of left subtree and right subtree, set the root.left to be the root of the left sub tree and root.right to be the root of the right sub tree. After this, we get a unique tree, add the root to the list.

Code:

/**
 * 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) {
        List<TreeNode> ret = new ArrayList<>();
        if(n == 0) return ret;
        return listTrees(1, n);
    }
    
    public List<TreeNode> listTrees(int start, int end){
        if(start > end){
            List<TreeNode> list = new ArrayList<>();
            list.add(null);
            return list;
        }
        if(start == end){
            List<TreeNode> list = new ArrayList<>();
            list.add(new TreeNode(start));
            return list;
        }
        List<TreeNode> list = new ArrayList<>();
        for(int i =  start; i <= end; i++){
            List<TreeNode> leftTrees = listTrees(start, i-1);
            List<TreeNode> rightTrees = listTrees(i+1, end);
            for(int j = 0; j < leftTrees.size(); j++){
                for(int k = 0; k < rightTrees.size(); k++){
                    TreeNode root = new TreeNode(i);
                    list.add(root);
                    root.left = leftTrees.get(j);
                    root.right = rightTrees.get(k);
                }
            }
        }
        return list;
    }
    
}

 

posted on 2016-01-27 10:06  爱推理的骑士  阅读(111)  评论(0编辑  收藏  举报