首页 > 代码库 > [LeetCode] Recover Binary Search Tree

[LeetCode] 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?

思路:中序递归的思路。用pre记录前一个节点,找出违反二叉搜索树规则的节点。中序遍历序列中,第一次违反二叉搜索树规则的节点的前一个节点是要修改的节点。第二次违反二叉搜索树规则的节点本身是要修改的节点

   时间复杂度O(n),空间复杂度O(1)

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     TreeNode *pre = NULL;13     TreeNode *mistake_node1 = NULL;14     TreeNode *mistake_node2 = NULL;15     16     void InorderTraversal(TreeNode *root) {17         if (root != NULL) {18             InorderTraversal(root->left);19             20             if (pre != NULL && root->val < pre->val) {21                 if (!mistake_node1) {22                     mistake_node1  = pre;23                     mistake_node2 = root;24                 } else {25                     mistake_node2 = root;26                 }27             }28             pre = root;29             InorderTraversal(root->right);30         }31     }32     void recoverTree(TreeNode *root) {33         InorderTraversal(root);34         if (mistake_node1 && mistake_node2)35             swap(mistake_node1->val, mistake_node2->val);36     }37 };

 

[LeetCode] Recover Binary Search Tree