Recover Binary Search Tree--leetcode难题讲解

本文介绍了一种解决二叉搜索树中两个节点被错误交换的问题的方法。通过使用递归中序遍历,我们可以找到错误的节点,并在不改变树结构的情况下进行修复。文章提供了Java、C++和Python三种语言的实现代码。

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

Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

https://leetcode.com/problems/recover-binary-search-tree/

二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。

最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作,但这个不符合空间复杂度要求。

需要用两个指针记录错误的那两个元素,然后进行交换。

怎样找出错误的元素?遍历二叉排序树,正确时应该是从小到大,如果出现之前遍历的节点比当前大,则说明出现错误。所以我们需要一个pre指针来指向之前经过的节点。

如果只有一处不符合从小到大,则只用交换这一个地方。第二个指针记录第二个异常点。

 

 Github repository: https://github.com/huashiyiqike/myleetcode 

//JAVA CODE:
public
class Solution { TreeNode first = null, second = null, pre = null; //first larger than follow, second smaller than pre public void helper(TreeNode root){ if(root.left != null) helper(root.left); if(pre != null && root.val < pre.val){ if(first == null) first = pre; second = root; } pre = root; if(root.right != null) helper(root.right); } public void recoverTree(TreeNode root) { helper(root); int tmp = first.val; first.val = second.val; second.val = tmp; } }

 

//C++ CODE:
#include <iostream> #include <cstdlib> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { TreeNode *first = NULL, *second = NULL, *last = NULL; public: void inorder(TreeNode* root){ if(root->left != NULL){ inorder(root->left); } if(last != NULL && root->val < last->val){ if(first == NULL) first = last; second = root; } last = root; if(root->right != NULL) inorder(root->right); } void recoverTree(TreeNode* root) { if(root == NULL) return; inorder(root); if(first && second) std::swap(first->val, second->val); } };
#PYTHON CODE:
class
Solution: def inorderTravel(self, root, last): if root.left: last = self.inorderTravel(root.left, last) if last and last.val > root.val: if self.first is None: self.first = last self.second = root last = root if root.right: last = self.inorderTravel(root.right, last) return last def recoverTree(self, root): if root is None: return self.first, self.second = None, None self.inorderTravel(root, None) self.first.val, self.second.val = self.second.val, self.first.val

 

转载于:https://www.cnblogs.com/huashiyiqike/p/4896163.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值