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?
解题思路:本题主要是考查了Morris Traversal,一种根据线索二叉树思想的时间复杂度为O(n),空间复杂度为O(1)的中序遍历方式。
在博客http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html里,原作者对Morris Traversal说的很明白。此题在此基础上只要比较相邻两个数的大小,就可以确定哪两个是打乱序的了。而Morris Traversal的中序输出就是原数组的从小到大排序,因而一切就变得简单了
/** * 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) { TreeNode *pre=NULL,*cur=root; TreeNode *first=NULL,*second=NULL,*temp=NULL; while(cur!=NULL){ if(cur->left==NULL){ //cur->val; if(temp!=NULL&&temp->val>cur->val){ if(!first)first=temp; second=cur; } temp=cur; cur=cur->right; } else { pre=cur->left; while(pre->right!=NULL&&pre->right!=cur) pre=pre->right; //exist threaded tree if(pre->right==cur){ //print cur->val; if(temp!=NULL&&temp->val>cur->val){ if(!first)first=temp; second=cur; } temp=cur; pre->right=NULL; cur=cur->right; } //creating backend poinner to the current point else{ pre->right=cur; cur=cur->left; } } } swap(first->val,second->val); } };
时间: 2024-10-11 10:59:24