[LeetCode]题解(python):095-Unique Binary Search Trees II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):095-Unique Binary Search Trees II相关的知识,希望对你有一定的参考价值。
题目来源:
https://leetcode.com/problems/unique-binary-search-trees-ii/
题意分析:
给一个整数,返回所有中序遍历是1到n的树。
题目思路:
这可以用递归的思想。首先确定根节点,如果k是根节点,那么1-k-1是左子树,而k+1-n为右子树。
代码(python):
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n == 0: return [] def solve(begin,end): if begin > end: return [None] i = begin ans = [] while i <= end: tmp1,tmp2 = solve(begin, i - 1),solve(i + 1,end) for j in tmp1: for k in tmp2: tmp = TreeNode(i) tmp.left = j tmp.right = k ans.append(tmp) i += 1 return ans return solve(1,n)
以上是关于[LeetCode]题解(python):095-Unique Binary Search Trees II的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]题解(python):112 Path Sum
[LeetCode]题解(python):133-Clone Graph
[LeetCode]题解(python):101-Symmetric Tree
[LeetCode]题解(python):101 Symmetric tree