1. 程式人生 > >LeetCode 99. Recover Binary Search Tree (BST重建)

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); } };