99. Recover Binary Search Tree

本文探讨了在二叉搜索树中两个节点错误交换的情况下,如何在不改变树结构的前提下,通过O(n)和常数空间复杂度的方法恢复树的正确状态。提供了详细的算法实现,包括中序遍历和值排序步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

99. Recover Binary Search Tree

Hard

99658FavoriteShare

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • A solution using O(n) space is pretty straight forward.
  • Could you devise a constant space solution?

Accepted

132,582

Submissions

366,722

/**
 * 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 recoverTree(TreeNode* root) {
        vector<int> in;
        vector<TreeNode*> intrees;
        intra(root,in,intrees);
        sort(in.begin(),in.end());
        for(int i=0;i<in.size();i++){
        	intrees[i]->val=in[i];//直接对指针所指对象进行修改
        }

    }
    void intra(TreeNode* root,vector<int>& in,vector<TreeNode*>& intrees){
    	if(root==NULL) return;
    	intra(root->left,in,intrees);
    	in.push_back(root->val);
    	intrees.push_back(root);
    	intra(root->right,in,intrees);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值