LeetCode 95. 不同的二叉搜索树 II

2021-09-15  本文已影响0人  陈陈chen

1、题目

image.png

2、分析

这个和第96题差不多,但是这里要求返回根节点的地址。还是用递归法,只不过把96题的解法稍微改一改

3、代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        return build(1, n);
    }

    private List<TreeNode> build(int lo, int hi){
        List<TreeNode> res = new LinkedList<TreeNode>();
        if(lo > hi) {
            res.add(null);
            return res;
        };
        //当以i作为root根节点时
        for(int i = lo; i <= hi; i++){
            List<TreeNode> leftTree = build(lo, i - 1);
            List<TreeNode> rightTree = build(i + 1, hi);
            //循环列举左右子树,和当前i作为root节点时,有多少种可能性
            for(TreeNode left: leftTree){
                for(TreeNode right: rightTree){
                    TreeNode node = new TreeNode(i);
                    node.left = left;
                    node.right = right;
                    res.add(node);
                }
            }
        }
        return res;
    }
}
上一篇下一篇

猜你喜欢

热点阅读