首页 > 编程语言 > 详细

[leetcode]Unique Binary Search Trees II @ Python

时间:2014-05-26 18:29:56      阅读:429      评论:0      收藏:0      [点我收藏+]

原题地址: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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!