给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
输入:[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 范围内的唯一整数值。
C++
class Solution {
public:
vector<int> arr;
void dfs(TreeNode* root){
if(root != nullptr){
dfs(root->left);
arr.push_back(root->val);
dfs(root->right);
}
}
TreeNode* increasingBST(TreeNode* root) {
//这里本来想用Lambda的写法,结果编译错误
// auto dfs = [&](TreeNode* root){
// if(root != nullptr){
// dfs(root->left);//由于lambda表达式的匿名特性,无法直接在lambda内部递归调用lambda,我们需要另寻其道来解决该问题。
// arr.push_back(root->val);
// dfs(root->right);
// }
// };
//中序遍历,结果存入vector容器中
dfs(root);
auto res = new TreeNode(arr[0]);
auto cur = res;
for(int i = 0; i < arr.size() - 1; i++){
cur->left = nullptr;
cur->right = new TreeNode(arr[i+1]);
cur = cur->right;
}
return res;
}
};