給定一個樹,按中序遍歷重新排列樹,使樹中最左邊的結點現在是樹的根,并且每個結點沒有左子結點,只有一個右子結點。
?
示例 :
輸入:[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* increasingBST(TreeNode* root){if (!root) return NULL;stack<TreeNode*> st;TreeNode* p = root , * s;int flag = 1;while (!st.empty() || p){while (p){st.push(p);p = p->left;}if (flag == 1){root = st.top();flag = 0;s = root;st.pop();p = s->right;}else{p = st.top();st.pop();p->left = NULL;s->right = p;s = p;p = p->right;}}return root;}
};
?