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

LeetCode: Recover Binary Search Tree [099]

时间:2014-06-02 10:38:17      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

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.



【题意】

给定的二叉搜索树中有两个节点的值错换了,找出这两个节点,恢复二叉搜索树。要求不适用额外的空间。


【思路】

中序遍历二叉树,一棵正常的二叉树中序遍历得到有序的序列,现有两个节点的值的调换了,则肯定是一个较大的值被放到了序列的前段,而较小的值被放到了序列的后段。节点的错换使得序列中出现了s[i-1]>s[i]的情况,如果错换的点正好是相邻的两个数,则s[i-1]>s[i]的情况只出现一次;如果不相邻,则会出现两次,第一次出现是前者为错换的较大值节点,第二次出现时后者为错换的较小值节点。


【代码】

/**
 * 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) {
        stack<TreeNode*> st;
        TreeNode* pointer=root;
        TreeNode* prev=NULL;
        TreeNode* nodeLarge=NULL;
        TreeNode* nodeSmall=NULL;
        while(pointer){st.push(pointer); pointer=pointer->left;}
        while(!st.empty()){
            TreeNode* cur = st.top();
            st.pop();
            if(prev && prev->val > cur->val){
                if(nodeLarge==NULL || prev->val > nodeLarge->val) nodeLarge=prev;
                if(nodeSmall==NULL || cur->val < nodeSmall->val) nodeSmall=cur;
            }
            prev=cur;
            pointer=cur->right;
            while(pointer){st.push(pointer); pointer=pointer->left;}
        }
        //替换两个节点的值
        int temp=nodeLarge->val;
        nodeLarge->val = nodeSmall->val;
        nodeSmall->val = temp;
    }
};


LeetCode: Recover Binary Search Tree [099],布布扣,bubuko.com

LeetCode: Recover Binary Search Tree [099]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/28092393

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