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

LeetCode: Recover Binary Search Tree

时间:2014-08-28 23:58:36      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   strong   ar   for   

LeetCode: Recover Binary Search Tree

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?

地址:https://oj.leetcode.com/problems/recover-binary-search-tree/

算法:二叉搜索树中有两个节点被错误的交换了,要求找到这两个节点,并把二者交换回来,要求用常数的空间。首先,使用中序遍历来搜索二叉树,当找到一个树比他的前趋还要小的时候,说明这个点是第一个错误点,即为A,然后接下去找第二个错误点,第二个错误点应该在第一个大于A点值的前面一个节点,记为B,接下去交换A,B节点即可。注意处理B点为最后一个节点时的情况。代码:

/**
 * 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) {
        if(!root)   return ;
        stack<TreeNode *> stk;
        TreeNode *p = root;
        while(p){
            stk.push(p);
            p = p->left;
        }
        TreeNode *pre = NULL;
        p = NULL;
        TreeNode *swapped_node1 = NULL;
        bool is_swapped = false;
        bool find_node = false;
        while(!stk.empty()){
            pre = p;
            p = stk.top();
            stk.pop();
            if(!find_node && pre && pre->val > p->val){
                swapped_node1 = pre;
                find_node = true;
            }
            if(find_node && p->val >= swapped_node1->val){
                if(pre){
                    int temp = swapped_node1->val;
                    swapped_node1->val = pre->val;
                    pre->val = temp;
                    is_swapped = true;
                    break;
                }
            }
            if(p->right){
                TreeNode *q = p->right;
                while(q){
                    stk.push(q);
                    q = q->left;
                }
            }
        }
        if(!is_swapped){
            int temp = swapped_node1->val;
            swapped_node1->val = p->val;
            p->val = temp;
        }
        return ;
    }
};

 

LeetCode: Recover Binary Search Tree

标签:style   blog   http   color   使用   io   strong   ar   for   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_recover_binary_search_tree.html

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