leetcode之recover-binary-search-tree(搜索二叉树BST重建)

leetcode之recover-binary-search-tree(搜索二叉树BST重建)

题目

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:
leetcode之recover-binary-search-tree(搜索二叉树BST重建)_第1张图片
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

题意

给定一颗二叉树,这个二叉树要求在O(n)的额外空间中,将其重新排序为一颗BTS,搜索二叉树。

解题思路

很明显我们要先明白BST搜索二叉树有什么规律,搜索二叉树就是一颗二叉树,满足条件所有的父节点小于左子树,大于右子树。所以说,这里可以采用重新给所有书的节点赋值的方法:
即:
1、BST的特性决定了这棵树的中序遍历是从左->右递增的,所以可以将这个二叉树当前先中序遍历一遍;
2、同步将被访问的节点入队列;
3、将中序遍历得到的值从小到大sort一遍;
4、重新将这些值,赋给队列里面的节点既可;

C++实现代码

/**
 * 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) {
        vector vec;
        vector node;
        Inorder(root,vec,node);
        sort(vec.begin(),vec.end());
        for(int i=0;ival = vec[i];
        }
    }
    void Inorder(TreeNode* root,vector &vec,vector &node){
        if(!root){
            return;
        }
        Inorder(root->left,vec,node);
        vec.push_back(root->val);
        node.push_back(root);
        Inorder(root->right,vec,node);
    }
};

你可能感兴趣的:(C++学习记录)