Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不同的二叉搜索树 II #74

Open
louzhedong opened this issue Oct 26, 2018 · 0 comments
Open

不同的二叉搜索树 II #74

louzhedong opened this issue Oct 26, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第95题

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

示例:

输入: 3
输出:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

思路

动态规划

解答

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number} n
 * @return {TreeNode[]}
 */
var generateTrees = function (n) {
  if (n === 0) return [];
  var dp = new Array(n + 1).fill(undefined).map(function () { return [] });
  dp[0].push(null);

  for (var i = 1; i <= n; i++) {
    for (var l = 0; l < i; l++) {
      var r = i - 1 - l;
      dp[l].forEach(function (left) {
        dp[r].forEach(function (right) {
          var root = new TreeNode(l + 1)
          root.left = left;
          root.right = cloneTree(right, l + 1);
          dp[i].push(root);
        })
      })
    }
  }
  return dp[n];
};

function cloneTree(root, offset) {
  if (!root) {
    return null;
  }

  const result = new TreeNode(root.val + offset);
  result.left = cloneTree(root.left, offset);
  result.right = cloneTree(root.right, offset);
  return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant