defgenerateTrees(self, n: int) -> List[TreeNode]: dp = [[] for _ inrange(n + 1)] dp[0] = [] if n == 0: return dp[0] dp[0].append(None) # 卡塔兰数第0个 forleninrange(1, n+1): # len是当前要求解的节点个数 dp[len] = [] for root inrange(1, len + 1): left = root - 1 right = len - root for leftTree in dp[left]: for rightTree in dp[right]: treeRoot = TreeNode(root) treeRoot.left = leftTree # 克隆右子树并且加上偏差 treeRoot.right = self.clone(rightTree, root) dp[len].append(treeRoot) return dp[n]
classBinarySearchTree: # 递归 中序遍历,左子树---> 根结点 ---> 右子树。 defInOder(self, root): """ In-Order Traversal of binary tree :param root: root node of target binary tree :return: TreeNode """ ifnot root: return [] # 空节点 res = [root.val] left_tree = self.InOder(root.left) right_tree = self.InOder(root.right) return left_tree + res + right_tree
# 广度优先遍历(基于队列/循环) defBreadthOrder(self, root): """ Breadth-first-Order Traversal of binary tree based on circulation :param root: root node of target binary tree :return: TreeNode """ queue = [] res = [] queue = [] # 入队 queue.append(i) # 出队 queue[0] queue[1:] 或者 queue.pop() # root inQueue 对象入队 queue.append(root) # 然后就循环出队root,root.left节点入队(先入先出),root.right节点再入队(后入后出),直到队列为空,结束循环。 whilelen(queue): t = queue.pop(0) # 不处理None模式的5行代码 # if t == None: # continue # queue.append(t.left) # queue.append(t.right) # res.append(t.val) # 处理None模式的6行代码 if t == None: res.append(None) # 空节点也放进去 else: queue.append(t.left) queue.append(t.right) res.append(t.val) return res
Input = [3] Answer = [5] if __name__ == "__main__": solution = Solution() BSTree = BinarySearchTree() for i inrange(len(Input)): print("-"*50) result = solution.generateTrees (Input[i]) for treenode in result: print(BSTree.BreadthOrder(treenode))
回溯算法的实现 最简洁的实现,推荐!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defgenerateTrees(self, n: int) -> List[TreeNode]: if n == 0: return [] return self.dfs(1, n)
defdfs(self, start, end): if start > end: return [None] res = [] for rootval inrange(start, end+1): LeftTree = self.dfs(start, rootval-1) RightTree = self.dfs(rootval+1, end) for i in LeftTree: for j in RightTree: root = TreeNode(rootval) root.left = i root.right = j res.append(root) return res
classSolution: defgenerateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ defgenerate_trees(start, end): if start > end: return [None,]
all_trees = [] for i inrange(start, end + 1): # pick up a root # all possible left subtrees if i is choosen to be a root left_trees = generate_trees(start, i - 1)
# all possible right subtrees if i is choosen to be a root right_trees = generate_trees(i + 1, end)
# connect left and right subtrees to the root i for l in left_trees: for r in right_trees: current_tree = TreeNode(i) current_tree.left = l current_tree.right = r all_trees.append(current_tree)