LeetCode-897. Increasing Order Search Tree
原创
©著作权归作者所有:来自51CTO博客作者ReignsDu的原创作品,请联系作者获取转载授权,否则将追究法律责任
Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
Output: [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
Note:
- The number of nodes in the given tree will be between 1 and 100.
- Each node will have a unique integer value from 0 to 1000.
题解:好坑啊。。。一直以为输入是二叉排序树。。。题目也不讲清楚
dfs疯狂WA
class Solution {
public:
TreeNode* increasingBST(TreeNode* root) {
TreeNode *p = root;
vector<int> v;
if (p == NULL) {
return NULL;
}
else {
dfs(p, v);
}
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
sort(v.begin(), v.end());
TreeNode *q = new TreeNode(v[0]);
TreeNode *ans = q;
for (int i = 1; i < v.size(); i++) {
q->right = new TreeNode(v[i]);
q = q->right;
}
return ans;
}
void dfs(TreeNode *p, vector<int> &v) {
if (p != NULL) {
v.push_back(p->val);
dfs(p->left, v);
dfs(p->right, v);
}
}
};
中序遍历ok了
class Solution {
public:
TreeNode* increasingBST(TreeNode* root) {
TreeNode *p = root;
vector<int> v;
if (p == NULL) {
return NULL;
}
else {
inorder(p, v);
}
TreeNode *q = new TreeNode(v[0]);
TreeNode *ans = q;
for (int i = 1; i < v.size(); i++) {
q->right = new TreeNode(v[i]);
q = q->right;
}
return ans;
}
void inorder(TreeNode *p, vector<int> &v) {
if (p != NULL) {
inorder(p->left, v);
v.push_back(p->val);
inorder(p->right, v);
}
}
};