首页 > 代码库 > 99. Recover Binary Search Tree
99. 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?
解题思路:本题主要是考查了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); } };
99. Recover Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。