# 897.increasing order search tree

897 Increasing Order Search Tree

5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9

1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9

/**
* 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 {
vector<TreeNode*> st;
void init_st(TreeNode* root)
{
if(root != NULL)
{
init_st(root->left);
st.push_back(root);
init_st(root->right);
}
}
public:
TreeNode* increasingBST(TreeNode* root) {
init_st(root);
for(int i=0;i<st.size()-1;i++)
{
st[i]->left =NULL;
st[i]->right=st[i+1];
}
return st[0];
}
};

• 采用中序遍历，先计算root左子树部分，新建一个TreeNode，每次递归调用时，将新建树list的右子连接到新建节点，然后list右移，计算root右子树部分。
/**
* 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:
void midTraverse(TreeNode* root, TreeNode* &list)
{
if (!root) return;
midTraverse(root->left, list);
TreeNode *newNode = new TreeNode(root->val);
list->right = newNode;
list = list->right;
midTraverse(root->right, list);
}
TreeNode* increasingBST(TreeNode* root)
{
TreeNode* newTree = new TreeNode(0);
TreeNode* res = newTree;
midTraverse(root, newTree);
return res->right;
}
};