标签:
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
首先是O(N)空间的方法,用递归:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void recoverTree(TreeNode* root) { 13 vt.clear(); 14 vi.clear(); 15 if(!root) return; 16 tranverse(root); 17 sort(vi.begin(), vi.end()); 18 for_each(vt.begin(), vt.end(), [this](TreeNode * t){static int i = 0; t->val = vi[i++];}); 19 } 20 21 void tranverse(TreeNode * root) 22 { 23 if(!root) return; 24 tranverse(root->left); 25 vt.push_back(root); 26 vi.push_back(root->val); 27 tranverse(root->right); 28 } 29 private: 30 vector<TreeNode *> vt; 31 vector<int> vi; 32 };
下面这个方法是看别人实现的,想法很好,维护两个指针,一个指向前面一个违反条件的,一个指向后面一个,q不断的进行更新,代码如下:
1 class Solution { 2 public: 3 void recoverTree(TreeNode* root) 4 { 5 p = q = prev = NULL; 6 if(!root) return; 7 tranverse(root); 8 swap(p->val, q->val); 9 } 10 11 void tranverse(TreeNode * root) 12 { 13 if(!root) return ; 14 tranverse(root->left); 15 if(prev && (prev->val > root->val)){ 16 if(!p) p = prev;//这里应该注意 17 q = root;//注意为什么q取的是root 18 } 19 prev = root; 20 tranverse(root->right); 21 } 22 private: 23 TreeNode * p, * q; 24 TreeNode * prev; 25 };
LeetCode OJ:Recover Binary Search Tree(恢复二叉搜索树)
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4918680.html