leetcode:Recover Binary Search Tree

来源:互联网 发布:sql怎么查平均数 编辑:程序博客网 时间:2024/05/16 10:22

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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

中序遍历,找出位置不正确的节点,记录下来,最后交换即可。

void help(TreeNode* root, TreeNode* &pre, TreeNode*&first, TreeNode*&second){if (root == NULL)return;help(root->left,pre, first, second);if (pre == NULL)pre = root;else{if (pre->val > root->val){if (first == NULL){first = pre;second = root;}else{second = root;return;}}pre = root;}help(root->right, pre, first, second);}void recoverTree(TreeNode *root) {TreeNode* pre = NULL;TreeNode* first = NULL, *second = NULL;if (root == NULL)return;help(root, pre, first, second);int tmp = first->val;first->val = second->val;second->val = tmp;}



0 0
原创粉丝点击