标签:
题目描述:(链接)
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?
解题思路:
空间复杂度是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 vector<TreeNode *> cache1; 14 stack<TreeNode *> cache2; 15 TreeNode *p = root; 16 17 while (!cache2.empty() || p != nullptr) { 18 if (p != nullptr) { 19 cache2.push(p); 20 p = p->left; 21 } else { 22 p = cache2.top(); 23 cache2.pop(); 24 cache1.push_back(p); 25 p = p->right; 26 } 27 } 28 29 int len = cache1.size(); 30 TreeNode *first; 31 for (int i = 0; i < len - 1; ++i) { 32 TreeNode *tmp1 = cache1[i]; 33 TreeNode *tmp2 = cache1[i + 1]; 34 if (tmp1->val > tmp2->val) { 35 first = tmp1; 36 break; 37 } 38 } 39 40 TreeNode *second; 41 for (int i = len - 1; i > 0; --i) { 42 TreeNode *tmp1 = cache1[i]; 43 TreeNode *tmp2 = cache1[i - 1]; 44 if (tmp1->val < tmp2->val) { 45 second = tmp1; 46 break; 47 } 48 } 49 50 if (first != nullptr && second != nullptr) { 51 swap(first->val, second->val); 52 } 53 } 54 };
[LeetCode]Recover Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/skycore/p/5011060.html