leetcode No99. Recover Binary Search Tree

来源:互联网 发布:端口数据监听工具 编辑:程序博客网 时间:2024/06/06 08:51

Question

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恢复成正确的

Algorithm

BST中序遍历的结果应该是顺序的,那么找到不是顺序的两个点交换就行。有可能只找到一个,这时交换此节点和它前面的一个节点。
二叉树的中序遍历:http://blog.csdn.net/u011391629/article/details/52201639

Accepted Code

class Solution {public:    void swap(TreeNode* x1,TreeNode* x2){        int tmp=x1->val;        x1->val=x2->val;        x2->val=tmp;    }    void recoverTree(TreeNode* root) {        stack<TreeNode*> s;        TreeNode* newRoot=root;        TreeNode* x1=NULL;        TreeNode* x2=NULL;        TreeNode* pre=NULL;        while(!s.empty() || root){            while(root){                s.push(root);                root=root->left;            }            if(!s.empty()){                root=s.top();                s.pop();                if(pre!=NULL && (pre->val>root->val)){                    if(x1==NULL){                        x1=pre;                        x2=root;                    }                    else{                        x2=root;                    }                }                pre=root;                root=root->right;            }        }        swap(x1,x2);    }};
原创粉丝点击