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);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章