题目描述:

给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。



示例 :

输入:[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 范围内的唯一整数值。

思想:构建一棵新树,代替原来的树

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* newroot, *curr;
TreeNode* increasingBST(TreeNode* root) {
if (root == NULL) return NULL;
increasingBST(root->left);
if (newroot == NULL) {
newroot = new TreeNode(root->val);
curr = newroot;
}
else {
curr->right = new TreeNode(root->val);
curr=curr->right;
}
increasingBST(root->right);
return newroot;
}
};

LeetCode_897_递增顺序查找树_构造函数


按照中序遍历,将树节点的值存入到vector中,然后遍历构建新树

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *ans,*pre;//定义指针节点,定义成成员变量,会调用默认的构造函数,赋值为NULL
void inorder(TreeNode* root,vector<int> &res){
if(root==NULL)
return ;
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
TreeNode* increasingBST(TreeNode* root) {
if(root==NULL)
return NULL;
vector<int> res;
inorder(root,res);
//TreeNode *ans,*pre;在内部,不会调用构造函数,必须赋予初始值NULL
for(int i=0;i<res.size();i++){
if(ans==NULL){
ans=new TreeNode(res[i]);;
pre=ans;
}
else{
pre->right=new TreeNode(res[i]);
pre=pre->right;
}
}
return ans;
}
};

LeetCode_897_递增顺序查找树_中序遍历_02