不同的二叉查找树 II

给出n,生成所有由1…n为节点组成的不同的二叉查找树

您在真实的面试中是否遇到过这个题?  Yes
样例

给出n = 3,生成所有5种不同形态的二叉查找树:

1         3     3       2    1
 \       /     /       / \    \
  3     2     1       1   3    2
 /     /       \                \
2     1         2                3

这和《不同的二叉查找树》差不多

代码:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
    public List<TreeNode> generateTrees(int n) {
        // write your code here
        if(n==0){
            List<TreeNode> R = new LinkedList<TreeNode>();
            R.add(null);
            return R;
        }
        return generateTrees(1,n);
    }
    private TreeNode copy(TreeNode Old){
        if(Old==null)
            return null;
        TreeNode T = new TreeNode(Old.val);
        T.right = copy(Old.right);
        T.left = copy(Old.left);
        return T;
    }
    List<TreeNode> generateTrees(int start, int last){
        if(start>last)
            return null;
        List<TreeNode> result = new LinkedList<TreeNode>();
        for(int i=start;i<=last;++i){
            TreeNode root = new TreeNode(i);
            List<TreeNode> left = generateTrees(start,i-1);
            List<TreeNode> right = generateTrees(i+1,last);
            if(left==null&&right==null)
                result.add(root);
            else if(left==null){
                for(TreeNode R:right){
                    root.right = R;
                    result.add(copy(root));
                }
            }
            else if(right==null){
                for(TreeNode L:left){
                    root.left = L;
                    result.add(copy(root));
                }
            }
            else{
                for(TreeNode L:left)
                    for(TreeNode R:right){
                        root.left = L;
                        root.right = R;
                        result.add(copy(root));
                    }
            }
        }
        return result;
    }
}
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/u014115273/article/details/51819209
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞