题目描述:

给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
示例:

  1. 输入: 3
  2. 输出:
  3. [
  4. [1,null,3,2],
  5. [3,2,null,1],
  6. [3,1,null,null,2],
  7. [2,1,3],
  8. [1,null,2,null,3]
  9. ]
  10. 解释:
  11. 以上的输出对应以下 5 种不同结构的二叉搜索树:
  12. 1 3 3 2 1
  13. \ / / / \ \
  14. 3 2 1 1 3 2
  15. / / \ \
  16. 2 1 2 3

代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {number} n
  10. * @return {TreeNode[]}
  11. */
  12. var generateTrees = function(n) {
  13. if (n === 0) return []
  14. if (n === 1) return [new TreeNode(1)]
  15. var res = [new TreeNode(1), new TreeNode(2)]
  16. res[0].right = new TreeNode(2)
  17. res[1].left = new TreeNode(1)
  18. var num = 3
  19. while (num <= n) {
  20. var cache = []
  21. res.forEach(root => {
  22. var newRoot = new TreeNode(num)
  23. newRoot.left = root
  24. cache.push(newRoot)
  25. var node = root
  26. while (node) {
  27. newN = new TreeNode(num)
  28. var newNode = new TreeNode(node.val)
  29. newNode.left = node.left
  30. newNode.right = newN
  31. newN.left = node.right
  32. var newRoot = node === root ? newNode : copyTree(root, newNode)
  33. cache.push(newRoot)
  34. node = node.right
  35. }
  36. })
  37. res = cache
  38. num++
  39. }
  40. return res
  41. function copyTree(root, target) {
  42. var res = new TreeNode(root.val), parent = res
  43. while (root.right) {
  44. var node = new TreeNode(root.right.val)
  45. if (root.right.val === target.val) {
  46. parent.right = target
  47. parent.left = root.left
  48. break
  49. }
  50. parent.right = node
  51. parent.left = root.left
  52. parent = node
  53. root = root.right
  54. }
  55. return res
  56. }
  57. };

不同的二叉搜索树Ⅱ - 图1