LeetCode 99. Recover Binary Search Tree (BST重建)

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • 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 {
    int i;
    void InOrderVis(TreeNode* root, vector<int>& node) {
        if(root) {
            InOrderVis(root->left, node);
            node.push_back(root->val);
            InOrderVis(root->right, node);
        }
    }
    
    void InOrderVisBuild(TreeNode* root, vector<int>& node) {
        if(root) {
            InOrderVisBuild(root->left, node);
            root->val = node[i++];
            InOrderVisBuild(root->right, node);
        }
    }
public:
    void recoverTree(TreeNode* root) {
        vector<int> node;
        InOrderVis(root, node);
        sort(node.begin(), node.end());
        i=0;
        InOrderVisBuild(root, node);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_26973089/article/details/83616862
今日推荐