码迷,mamicode.com
首页 > 编程语言 > 详细

99. Recover Binary Search Tree -- 找到二叉排序树中交换过位置的两个节点

时间:2016-04-20 11:34:36      阅读:127      评论: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?

/**
 * Definition for a binary tree node.
 * 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*> s;
        TreeNode *p = root, *last = NULL, *p1 = NULL, *p2 = NULL;
        while(p || !s.empty())
        {
            while(p)
            {
                s.push(p);
                p = p->left;
            }
            if(!s.empty())
            {
                p = s.top();
                s.pop();
                if(last && last->val >= p->val)
                {
                    p2 = p;
                    if(!p1)
                        p1 = last;
                    else
                        break;
                }
                last = p;
                p = p->right;
            }
        }
        swap(p1->val, p2->val);
    }
};

 

99. Recover Binary Search Tree -- 找到二叉排序树中交换过位置的两个节点

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5411678.html

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