【发布时间】:2020-12-24 07:02:13
【问题描述】:
这是来自leetcode 的问题。 它说
给定二叉搜索树的根,重新排列树 有序,使得树中最左边的节点现在是 树,每个节点没有左孩子,只有一个右孩子。
示例 2,
我的代码和下面的差不多,
void inorder(struct TreeNode *root, struct TreeNode **newRoot)
{
if (root == NULL)
return;
inorder(root->left, newRoot);
(*newRoot)->left = NULL;
(*newRoot)->right = root;
*newRoot = (*newRoot)->right;
inorder(root->right, newRoot);
return;
}
struct TreeNode* increasingBST(struct TreeNode *root)
{
struct TreeNode *newRoot = calloc(1, sizeof(struct TreeNode));
struct TreeNode *result = newRoot;
inorder(root, &newRoot);
//newRoot->left = NULL;
//newRoot->right = NULL;
return result->right;
}
在输入 [2,1,4,null,null,3] 之前,它适用于多个输入。 实际上,它最终返回了,但我仍然收到“超出时间限制”错误。 我发现有一个类似的解决方案,但它激活了上面的两行,
newRoot->left = NULL;
newRoot->right = NULL;
然后就可以了。 我不明白这两行为什么那么重要。 请对此有所了解。
【问题讨论】:
标签: tree binary-tree binary-search-tree