首页 > 其他 > 详细

Recover Binary Search Tree

时间:2014-04-11 08:10:33      阅读:537      评论:0      收藏:0      [点我收藏+]

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?

Solution: 1. recursive solution. O(n) space. get inorder list first.
2. recursive solution. O(n) space. with only auxiliary two pointers.
3. Morris inorder traversal. O(1) space. with only auxiliary two pointers.

bubuko.com,布布扣
 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 recoverTree(TreeNode *root) {
13         TreeNode* prev = NULL;
14         TreeNode* first = NULL;
15         TreeNode* second = NULL;
16         recoverTreeRe(root, prev, first, second);
17         swap(first->val, second->val);
18     }
19     
20     void recoverTreeRe(TreeNode* root, TreeNode* &prev, TreeNode* &first, TreeNode* &second)
21     {
22         if(!root) return;
23         recoverTreeRe(root->left, prev, first, second);
24         if(prev && prev->val > root->val) {
25             if(!first) {
26                 first = prev;
27             }
28             second = root;
29         }
30         prev = root;
31         recoverTreeRe(root->right, prev, first, second);
32     }
33 };
bubuko.com,布布扣

 

Recover Binary Search Tree,布布扣,bubuko.com

Recover Binary Search Tree

原文:http://www.cnblogs.com/zhengjiankang/p/3657846.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!