您的位置:首页 > 其它

[LeetCode] Recover Binary Search Tree

2015-01-21 22:03 225 查看
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?

思路:中序递归的思路。用pre记录前一个节点,找出违反二叉搜索树规则的节点。中序遍历序列中,第一次违反二叉搜索树规则的节点的前一个节点是要修改的节点。第二次违反二叉搜索树规则的节点本身是要修改的节点.如果是中序遍历相邻的节点出错直接两次都违反。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
if (root == NULL) return;

stack<TreeNode*> s;
TreeNode* p = root;
TreeNode* pre = NULL;
TreeNode* wrong_node1 = NULL;
TreeNode* wrong_node2 = NULL;
int flag = 1;

while (p != NULL || !s.empty()) {
if (p != NULL) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
if (pre == NULL) {
pre = p;
} else {
if (pre->val > p->val) {
if (flag == 1) {
wrong_node1 = pre;
wrong_node2 = p;
flag = 2;
} else {
wrong_node2 = p;
}
}
pre = p;
}
p = p->right;
}
}

int temp = wrong_node1->val;
wrong_node1->val = wrong_node2->val;
wrong_node2->val = temp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: