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

leetcode笔记:Recover Binary Search Tree

时间:2015-10-21 07:05:38      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   bst   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?

二. 题目分析

题目的大意是,在二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。

一个最简单的办法是,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。这种方法的空间复杂度为O(n)

但是,题目中要求空间复杂度为常数,所以需要换一种方法。

递归中序遍历二叉树,设置一个prev指针,记录当前节点中序遍历时的前节点,如果当前节点大于prev节点的值,说明需要调整次序。

三. 示例代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
TreeNode *p,*q;
TreeNode *prev;
    void recoverTree(TreeNode *root)
    {
        p=q=prev=NULL;
        inorder(root);
        swap(p->val,q->val);      
    }
    void inorder(TreeNode *root)
    {
        if(root->left)inorder(root->left);
        if(prev!=NULL&&(prev->val>root->val))
        {
            if(p==NULL)p=prev;
            q=root;
        }
        prev=root;
        if(root->right)inorder(root->right);
    }
};

四. 小结

有一个技巧是,若遍历整个序列过程中只出现了一次次序错误,说明就是这两个相邻节点需要被交换。如果出现了两次次序错误,那就需要交换这两个节点。

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode笔记:Recover Binary Search Tree

标签:leetcode   c++   bst   tree   排序   

原文地址:http://blog.csdn.net/liyuefeilong/article/details/49287049

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