[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) 空间的解法是,开一个指针数组,中序遍历,将节点指针依次存放到数组里,然后寻找两处逆向的位置,

先从前往后找第一个逆序的位置,然后从后往前找第二个逆序的位置,交换这两个指针的值。

【代码】

/*********************************
*   日期:2014-12-10
*   作者:SJF0115
*   题号: Recover Binary Search Tree
*   来源:https://oj.leetcode.com/problems/recover-binary-search-tree/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <malloc.h>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void InOrder(TreeNode *root){
    if(root == NULL){
        return;
    }
    InOrder(root->left);
    cout<<root->val<<endl;
    InOrder(root->right);
}

class Solution {
public:
    void recoverTree(TreeNode *root) {
        stack<TreeNode*> stack;
        vector<TreeNode*> v;
        // 错乱节点
        TreeNode *first,*second;
        if(root == NULL){
            return;
        }
        TreeNode *p = root;
        // 中序遍历
        while(p != NULL || !stack.empty()){
            // 不空一直向左子树走
            if(p){
                stack.push(p);
                p = p->left;
            }
            // 转向右子树
            else{
                p = stack.top();
                stack.pop();
                v.push_back(p);
                p = p->right;
            }//if
        }//while
        // 从前向后遍历
        for(int i = 0;i < v.size();i++){
            if((v[i])->val > (v[i+1])->val){
                first = v[i];
                break;
            }
        }
        // 从后向前遍历
        for(int i = v.size()-1;i >= 0;i--){
            if((v[i])->val < (v[i-1])->val){
                second = v[i];
                break;
            }
        }
        // 交换错误节点
        /*int tmp;
        tmp = first->val;
        first->val = second->val;
        second->val = tmp;*/
        swap(first->val,second->val);
    }
};

//按先序序列创建二叉树
int CreateBTree(TreeNode* &T){
    char data;
    //按先序次序输入二叉树中结点的值(一个字符),‘#’表示空树
    cin>>data;
    if(data == '#'){
        T = NULL;
    }
    else{
        T = (TreeNode*)malloc(sizeof(TreeNode));
        //生成根结点
        T->val = data-'0';
        //构造左子树
        CreateBTree(T->left);
        //构造右子树
        CreateBTree(T->right);
    }
    return 0;
}

int main() {
    Solution solution;
    TreeNode* root(0);
    CreateBTree(root);
    solution.recoverTree(root);
    InOrder(root);
}

时间: 2024-07-28 18:45:33

[LeetCode]99.Recover Binary Search Tree的相关文章

[LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary

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}&qu

[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

[LeetCode]95.Unique Binary Search Trees II

[题目] Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 confused what "

[LeetCode]96.Unique Binary Search Trees

[题目] Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 [分析] 如果把上例的顺序改一下,就可以看出规律了. 比如,以 1 为根的树的个数

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