题目:
Given the root
of a binary search 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 one right child.
Example 1:
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:
Input: root = [5,1,7] Output: [1,null,5,null,7]
Constraints:
- The number of nodes in the given tree will be in the range
[1, 100]
. 0 <= Node.val <= 1000
思路:
常规的话用一个数组记录中序遍历的结果,获得从小到大排序的数组,然后重新造一个list返回即可,数据量不大,能通过。这里讲一下原地操作不用额外space的方法。逻辑上就是用左边的node来替代现有node。首先如果root为空则返回空,如果左子为空,则说明接下来的都是右边的,那当前的root就是最小值,它应该是最终的root,那只要递归一下然后返回当前root即可。否则有左子的话用新node记录左子,这个新node就作为下一个root,然后把左子的右边挂到当前root的左边,新node的右子挂到当前root上。以例一为例,走到5时,把3作为新node,4挂到3的位置,然后3的右子挂到5,此时1,2,3在5的左上方,4是5的左子,然后继续递归3,最后1会变成root,返回最终的root。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* increasingBST(TreeNode* root) {
if(!root)
return NULL;
if(!root->left)
{
root->right=increasingBST(root->right);
return root;
}
TreeNode* nroot =root->left;
root->left=nroot->right;
nroot->right=root;
return increasingBST(nroot);
}
};