Leetcode95

2018-11-05  本文已影响0人  zhouwaiqiang

题目要求

给定一个正整数n,求出它所产生的所有的二叉查找树(左边比根节点小,右边比根节点大),其数的组合由1-n

实现过程(给出的solution方法,个人理解)

代码复现

public class Solution {
    public List<TreeNode> generateTree(int n) {
        if (n == 0) return new ArrayList<TreeNode>();
        return generate_tree(1, n);
    }
    
    private static List<TreeNode> generate_tree(int start, int end) {
        List<TreeNode> result = new ArrayList<>();
        if (start > end) return result.add(null);
        for (int i=start; i<=end; i++) {
            List<TreeNode> left_trees = genenrate_tree(start, i-1);
            List<TreeNode> right_trees = generate_tree(i+1, end);
            for (TreeNode l : left_trees) {
                for (TreeNode r : right_trees) {
                    TreeNode current_node = new TreeNode(i);
                    current_node.left = l;
                    current_node.right = r;
                    result.add(current_node);
                }
            }
        }
        return result;
    }
}

个人博客链接

http://www.waiqiang.ren/

上一篇下一篇

猜你喜欢

热点阅读