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?

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

 

这道题是要求恢复一颗有两个元素调换错了的二叉查找树。一开始拿到可能会觉得比较复杂,其实观察出规律了就比较简单。主要还是利用二叉查找树的主要性质,就是中序遍历是有序的性质。那么如果其中有元素被调换了,意味着中序遍历中必然出现违背有序的情况。那么会出现几次呢?有两种情况,如果是中序遍历相邻的两个元素被调换了,很容易想到就只需会出现一次违反情况,只需要把这个两个节点记录下来最后调换值就可以;如果是不相邻的两个元素被调换了,举个例子很容易可以发现,会发生两次逆序的情况,那么这时候需要调换的元素应该是第一次逆序前面的元素,和第二次逆序后面的元素。比如1234567,1和5调换了,会得到5234167,逆序发生在52和41,我们需要把4和1调过来,那么就是52的第一个元素,41的第二个元素调换即可。
搞清楚了规律就容易实现了,中序遍历寻找逆序情况,调换的第一个元素,永远是第一个逆序的第一个元素,而调换的第二个元素如果只有一次逆序,则是那一次的后一个,如果有两次逆序则是第二次的后一个。算法只需要一次中序遍历,所以时间复杂度是O(n),空间是栈大小O(logn)。

C++代码如下: 

#include<iostream>
#include<new>
using namespace std;

//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 *first=NULL;
    TreeNode *second=NULL;
    TreeNode *pre=NULL;
    void recoverTree(TreeNode *root)
    {
        recoverInorder(root);
        swap(first->val,second->val);
    }
    void recoverInorder(TreeNode *root)
    {
        if(root)
        {
            recoverInorder(root->left);
            if(pre&&pre->val>root->val)
            {
                if(first==NULL)
                {
                    first=pre;
                    second=root;
                }
                else
                    second=root;
            }
            pre=root;
            recoverInorder(root->right);
        }
    }
    void createTree(TreeNode *&root)
    {
        int arr[10]= {5,9,7,8,6,10,4,2,1,3};
        int i;
        for(i=0; i<10; i++)
            insert(root,arr[i]);
    }
    void insert(TreeNode *&root,int key)
    {
        TreeNode *tmp=new TreeNode(key);
        if(root==NULL)
        {
            root=tmp;
        }
        else if(key<root->val)
            insert(root->left,key);
        else
            insert(root->right,key);
    }
    void inorder(TreeNode *root)
    {
        if(root)
        {
            inorder(root->left);
            cout<<root->val<<" ";
            inorder(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode *root=NULL;
    s.createTree(root);
    s.inorder(root);
    cout<<endl;
    swap(root->left->val,root->right->val);
    s.inorder(root);
    cout<<endl;
    s.recoverTree(root);
    s.inorder(root);
}

运行结果:

时间: 2024-10-27 06:47:50

Recover Binary Search Tree的相关文章

[LeetCode]99.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? [解析] O(n) 空间的解法是,开一个指针数组

Geeks 面试题之Optimal Binary Search Tree

Dynamic Programming | Set 24 (Optimal Binary Search Tree) Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches to keys[i]. Construct a binary search tree of all keys

算法:uva-10304 Optimal Binary Search Tree(区间dp)

题意 给一个序列即可 S = (e1,e2,...,en),且e1<e2<..<en.要把这些序列构成一个二叉搜索 树. 二叉搜索树是具有递归性质的,且若它的左子树不空,则左子树上所有结点的值均小于它的根结点的 值: 若它 的右子树不空,则右子树上所有结点的值均大于它的根结点的值. 因为在实际应用中,被访 问频率越高的元素,就应该越接近根节点,这样才能更加节省查找时间. 每个元素有一个访问频率f(ei) ,当元素位于深度为k的地方,那么花费cost(ei) = k. 所有节点的花费和访问

二叉查找树(binary search tree)详解

二叉查找树(Binary Search Tree),也称二叉排序树(binary sorted tree),是指一棵空树或者具有下列性质的二叉树: 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值 任意节点的左.右子树也分别为二叉查找树 没有键值相等的节点(no duplicate nodes) 本文地址:http://www.cnblogs.com/archimedes/p/binary-search-tree

[LeetCode]235.Lowest Common Ancestor of a Binary Search Tree

题目 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that h

[LeetCode]173.Binary Search Tree Iterator

[题目] Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and

[LeetCode]109.Convert Sorted List to Binary Search Tree

[题目] Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. [分析] 无 [代码] 在下面超时的代码上进行改进:把链表先转换为vector再进行操作. [LeetCode]108.Convert Sorted Array to Binary Search Tree /*******************************

[LeetCode]108.Convert Sorted Array to Binary Search Tree

[题目] Given an array where elements are sorted in ascending order, convert it to a height balanced BST. [分析] 二分法,以中间元素i为根节点[start,i-1]递归构建左子树,[i+1,end]递归构建右子树 [代码] /********************************* * 日期:2014-12-28 * 作者:SJF0115 * 题目: 108.Convert Sorte

Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys