标签:
若乱序。就将这两个结点都放入到预先定义的容器中。
//store disorder nodes, most of the number is 4. vector<TreeNode*> outorder; //point to the last node of inorder sequence TreeNode *pre = NULL; void visitInorder(TreeNode* root){ if(root == NULL) return; if(root->left) visitInorder(root->left); if(pre == NULL) pre = root; else if(root->val < pre->val){ outorder.push_back(pre); outorder.push_back(root); } //move pre to the new tail. pre = root; if(root->right) visitInorder(root->right); } void recoverTree(TreeNode *root) { if( NULL == root ) return; visitInorder(root); if(outorder.size()) { swap(outorder[0]->val, outorder[outorder.size() - 1]->val); } }
版权声明:本文博主原创文章,博客,未经同意不得转载。
【leetcode】Recover Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/lcchuguo/p/4795601.html