[LeetCode] 078: Recover Binary Search Tree

来源:互联网 发布:点餐系统数据库设计 编辑:程序博客网 时间:2024/05/21 11:17
[Problem]

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?

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1  / \ 2   3    /   4    \     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

[Solution]
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode *root, TreeNode* &pre, TreeNode* &first, TreeNode* &second){
if(NULL == root)return ;

// visit the left brunch
inorder(root->left, pre, first, second);

// visit the root
if(pre != NULL && pre->val > root->val){
if(first == NULL){
first = pre;
}
second = root;
}
pre = root;

// visit the right brunch
inorder(root->right, pre, first, second);
}
void recoverTree(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(NULL == root)return;

// initial
TreeNode* pre = NULL;
TreeNode* first = NULL;
TreeNode* second = NULL;

// inorder
inorder(root, pre, first, second);
if(first != NULL && second != NULL){
first->val ^= second->val;
second->val ^= first->val;
first->val ^= second->val;
}
}
};
说明:版权所有,转载请注明出处。Coder007的博客