在BST树的问题中,学会运用中序遍历来检验内中项的对错,是十分重要的
有时可能会成为超级简洁并方便的一个方法。
比如下面这一题,
网址:https://leetcode.com/problems/recover-binary-search-tree/#/description
题目:Recover Binary Search Tree
描述:
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?
将BST树中倒序的两项找出并交换
本想在找出一项后,在根据BST树性质确定其位置交换,但却遇到了很多的问题,代码缠作一团
参考了dalao的代码之后,感受到了中序遍历的强大:
class Solution {
TreeNode* first=NULL;
TreeNode* second=NULL;
TreeNode* prev = new TreeNode(INT_MIN);
public:
void recoverTree(TreeNode* root) {
help(root);
swap(first->val, second->val);
}
void help(TreeNode* root){
if(root==NULL) return;
help(root->left);
if(first==NULL && prev->val >= root->val) first=prev;
if(first!=NULL && prev->val >= root->val) second=root;
prev=root;
help(root->right);
}
};