[leetcode]Unique Binary Search Trees II @ Python


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

題意:接上一題,這題要求返回的是所有符合條件的二叉查找樹,而上一題要求的是符合條件的二叉查找樹的棵數,我們上一題提過,求個數一般思路是動態規划,而枚舉的話,我們就考慮dfs了。dfs(start, end)函數返回以start,start+1,...,end為根的二叉查找樹。

代碼:

# 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM