95. 不同的二叉搜索树 II
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<TreeNode> generateTrees(int n) { List<TreeNode> pre = new ArrayList<TreeNode>(); if(n == 0) return pre; pre.add(null); for (int i = 1; i <= n; i++) { List<TreeNode> cur = new ArrayList<TreeNode>(); for (TreeNode root : pre){ TreeNode node = new TreeNode(i); node.left = root; cur.add(node); for (int j = 0; j < n ; j++) { TreeNode copyRoot = copyTree(root); TreeNode findPos = copyRoot; for (int k = 0; k < j; k++) { if(findPos != null) findPos = findPos.right; else break; } if(findPos == null) break; node = new TreeNode(i); node.left = findPos.right; findPos.right = node; cur.add(copyRoot); } } pre = cur; } return pre; } private TreeNode copyTree(TreeNode root){ if(root == null) return null; TreeNode newRoot = new TreeNode(root.val); newRoot.left = copyTree(root.left); newRoot.right = copyTree(root.right); return newRoot; } }
python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def generateTrees(self, n: int) -> List[TreeNode]: pre = [] if n == 0: return pre pre.append(None) for i in range(1, n+1): cur = [] for root in pre: node = TreeNode(val= i) node.left = root cur.append(node) for j in range(0, n): copyRoot = self.copyTree(root) findPos = copyRoot for k in range (0, j): if findPos is not None: findPos = findPos.right else : break if findPos is None: break node = TreeNode(i) node.left = findPos.right findPos.right = node cur.append(copyRoot) pre = cur return pre def copyTree(self, root:TreeNode)-> TreeNode: if root is None: return None newRoot = TreeNode(root.val) newRoot.left = self.copyTree(root.left) newRoot.right = self.copyTree(root.right) return newRoot