码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Recover Binary Search Tree

时间:2015-07-16 00:41:35      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

As the note in the problem statement, this problem has a straight-forward O(n)-space solution, which is to generate the inorder traversal results of the bst and then find the two nodes that violate the increasing trend and those are the two that requires to be swapped.

This link utilizes inorder traversal to find those two nodes without keeping all the results. However, inorder traversal implemented recursively will take at least O(logn) space and may even take O(n) space at the worst case. The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     void recoverTree(TreeNode* root) {
 4         pre = first = second = NULL;
 5         inorder(root);
 6         if (first) {
 7             int temp = first -> val;
 8             first -> val = second -> val;
 9             second -> val = temp;
10         }
11     }
12 private:
13     TreeNode *first, *second, *pre;
14     void inorder(TreeNode* root) {
15         if (!root) return;
16         inorder(root -> left);
17         if (pre && pre -> val > root -> val) {
18             if (!first) first = pre;
19             second = root;
20         }
21         pre = root;
22         inorder(root -> right);
23     }
24 };

So to come up with an O(1)-space solution, we indeed have to turn to Morris traversal...

[LeetCode] Recover Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4649828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!