[Leetcode] 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?

 

中序遍历,对于BST,其中序序列是有序的,所以只要找出中序序列中的逆序对,但是要注意保存中间节点,可以使用全局变量,也可以使用引用。

 1 /**
 2  * Definition for binary tree
 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 inorder(TreeNode *root, TreeNode *&pos1, TreeNode *&pos2, TreeNode *&pre) {
13         if (root == NULL) return;
14         inorder(root->left, pos1, pos2, pre);
15         if (pre != NULL && pre->val > root->val) {
16             if (pos1 == NULL) {
17                 pos1 = pre;
18                 pos2 = root;
19             } else {
20                 pos2 = root;
21             }
22         }
23         pre = root;
24         inorder(root->right, pos1, pos2, pre);
25     }
26     
27     void recoverTree(TreeNode *root) {
28         TreeNode *pos1, *pos2, *pre;
29         pos1 = pos2 = pre = NULL;
30         inorder(root, pos1, pos2, pre);
31         swap(pos1->val, pos2->val);
32     }
33 };

 

posted @ 2014-04-04 00:49  Eason Liu  阅读(252)  评论(0编辑  收藏  举报