码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Unique Binary Search Trees II @ Python

时间:2014-05-26 18:30:01      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

原题地址:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/

题意:接上一题,这题要求返回的是所有符合条件的二叉查找树,而上一题要求的是符合条件的二叉查找树的棵数,我们上一题提过,求个数一般思路是动态规划,而枚举的话,我们就考虑dfs了。dfs(start, end)函数返回以start,start+1,...,end为根的二叉查找树。

代码:

bubuko.com,布布扣
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @return a list of tree node
    def dfs(self, start, end):
        if start > end: return [None]
        res = []
        for rootval in range(start, end+1):        #rootval为根节点的值,从start遍历到end
            LeftTree = self.dfs(start, rootval-1)
            RightTree = self.dfs(rootval+1, end)
            for i in LeftTree:                #i遍历符合条件的左子树
                for j in RightTree:              #j遍历符合条件的右子树
                    root = TreeNode(rootval)
                    root.left = i
                    root.right = j
                    res.append(root)
        return res
    def generateTrees(self, n):
        return self.dfs(1, n)
bubuko.com,布布扣

 

[leetcode]Unique Binary Search Trees II @ Python,布布扣,bubuko.com

[leetcode]Unique Binary Search Trees II @ Python

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3752428.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!