leetcode-95-Unique Binary Search Trees II

题目解读: 穷举列出所有二叉树的结构类型。

重点: 动态规划,关注临近root,left,right之间的关系

应用:穷举组合,动态规划穷举组合,适用于相邻元素有规律。

bug处:注意边界值的情况。不能有重复,遗漏。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def generateTrees(self, n):
        def dfs(left,right):
            nodes=list()
            for root in range(left,right+1):
                print('root=>',root)
                # node=TreeNode(root)
                for node_left in dfs(left,root-1):
                    # node_left=TreeNode(val_left)
                    for node_right in dfs(root+1,right):
                        node_root=TreeNode(root)
                        node_root.left=node_left
                        # node_right=TreeNode(val_right)
                        node_root.right=node_right
                        # nodes.append(node_root)
                        nodes.append(node_root)
            return nodes or [None,]
        if n<1:
            return []
        return dfs(1,n)

if __name__=='__main__':
    n=0
    st=Solution()
    out=st.generateTrees(n)
    # out_vals=[(elem.left.val if hasattr(elem.left,'val') else None,elem.right.val if hasattr(elem.right,'val') else None) for elem in out]
    print(out)
    print(len(out))
    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000015987935
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞