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

Recover Binary Search Tree

时间:2014-12-03 21:14:01      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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?

/**
 * 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 recoverTree(TreeNode *root) {
        node1 = node2 = NULL;
        prev = new TreeNode(INT_MIN);
        check(root);
        int tmp = node1->val;
        node1->val = node2->val;
        node2->val = tmp;
    }
    void check(TreeNode *root){
        if(root == NULL) return;
        check(root->left);
        if(node1 == NULL && prev->val >= root->val){
            node1 = prev;
        }
        if(node1 != NULL && prev->val >= root->val){
            node2 = root;
        }
        prev = root;
        check(root->right);
    }
    
    TreeNode *node1, *node2, *prev;
};

 

Recover Binary Search Tree

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/code-swan/p/4141172.html

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