递增顺序查找树
原题:
给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]5/ \3 6/ \ \2 4 8/ / \1 7 9输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]1\2\3\4\5\6\7\8\9
提示:
- 给定树中的结点数介于
1和100之间。 - 每个结点都有一个从
0到1000范围内的唯一整数值。
解题方法:
解法一:
class Solution {
public:
TreeNode* node;
queue<int> que;
TreeNode* increasingBST(TreeNode* root) {
if(!root) return root;
auto ans=new TreeNode(0);
node=ans;
inOrder(root);
while(!que.empty())
{
node->right=new TreeNode(que.front());
que.pop();
node=node->right;
}
return ans->right;
}
void inOrder(TreeNode* root)
{
if(!root) return;
inOrder(root->left);
que.push(root->val);
inOrder(root->right);
}
};
解法二:
class Solution {
public:
TreeNode* node;
TreeNode* increasingBST(TreeNode* root) {
if(!root) return root;
auto ans=new TreeNode(0);
node=ans;
inOrder(root);
return ans->right;
}
void inOrder(TreeNode* root)
{
if(!root) return;
inOrder(root->left);
root->left=nullptr;
node->right=root;
node=node->right;
inOrder(root->right);
}
};
做题小结:
针对解法一:
- 自己做的时候思路是正确的,即先中序遍历把所有数值存储下来,然后再依次取出来建树
- 建树的方法不知道,导致卡了很久,建树应该直接new TreeNode(val)来创建结点,我却一直在想办法用TreeNode 。而且建树的时候要注意*先给node->right赋值,再node=node->right,这样才能保证树是接上的
针对解法二:
- 同样的问题,就是不知道该怎么建树,这下长记性了🙃
- 需要注意的是直接对原树进行重排,不能忘了把左节点置为nullptr
