897. Increasing Order Search Tree

题目:

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);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值