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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
递归,本以为用递归会超时呢,居然没有。。。
有一点需要注意,只要当前子树中的左子树中的结点和根或者右子树中的值交换,换完之后都将是左子树中的最大值。右子树同理,是右子树中的最小值。
如果交换是左子树中的两个值交换,即交换不跨越当前根节点,就交给递归吧。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* findLargestInLeft(TreeNode* root) { if(root==NULL) return NULL; TreeNode* left = NULL; TreeNode* right = NULL; if(root->left) left = findLargestInLeft(root->left); if(root->right) right = findLargestInLeft(root->right); if(left && right) { TreeNode* largest = root->val > left->val ? root : left; largest = largest->val > right->val ? largest : right; return largest; }else if(left && right==NULL) { return root->val > left->val ? root : left; }else if(left==NULL && right) { return root->val > right->val ? root : right; }else return root; } TreeNode* findLeastInRight(TreeNode* root) { if(root ==NULL) return NULL; TreeNode* left = NULL; TreeNode* right = NULL; if(root->left != NULL) left = findLeastInRight(root->left); if(root->right) right = findLeastInRight(root->right); if(left && right) { TreeNode* least = root->val < left->val ? root : left; least = least->val < right->val ? least : right; return least; }else if(left && right == NULL) { return root->val < left->val ? root : left; }else if(left == NULL && right) { return root->val < right->val ? root : right; }else return root; } void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL)return; TreeNode* left = findLargestInLeft(root->left); TreeNode* right = findLeastInRight(root->right); if(left && right){ if(left->val > root->val && root->val > right->val) swap(left->val, right->val); else if(root->val < left->val && left->val < right->val) swap(left->val, root->val); else if(left->val < right->val && right->val < root->val) swap(root->val, right->val); else{ recoverTree(root->left); recoverTree(root->right); } }else if(left != NULL && right==NULL){ if(root->val < left->val) swap(root->val, left->val); else recoverTree(root->left); }else if(left==NULL && right!=NULL){ if(root->val > right->val) swap(root->val, right->val); else recoverTree(root->right); } } };