[LeetCode-75]Recover Binary Search Tree
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. Analysis: The question requires O(1) space, let's first consider the case without this. How to traverse BST? Yep! The inOrder tree traversal. (left->root->right) So the easiest way is inorder traverse the BST and find the element pair (two elements) which are not consistent with the definition of BST. In order to get the order, a queue is needed, which is O(n). Or we could just sort the result of the order and revalue the BST.
O(n) solution
void inorderBST(TreeNode *root, vector<int> &result, vector<TreeNode*> &list){
if(root!=NULL){
inorderBST(root->left,result,list);
list.push_back(root);
result.push_back(root->val);
inorderBST(root->right,result,list);
}
}
void recoverTree(TreeNode *root) {
vector<int> result;
vector<TreeNode*> nodelist;
inorderBST(root,result,nodelist);
sort(result.begin(),result.end());
for(int i=0;i<nodelist.size();i++){
nodelist[i]->val = result[i];
}
}
Now how to do this procedure in O(1)?
What we need is actually two pointers, which point to 2 tree nodes where is incorrect. Therefore, we only need to store these two pointers, and, we also need another pointer to store the previous element, in order to compare if the current element is valid or not.
In the code below, you will find, the last step is to replace the wrong pair's value. And the inOrder function is to search the whole BST and find the wrong pairs.
Note that, (1)the previous element is NOT the root node of the current element, but the previous element in the "inOrder"order; (2) To store the wrong pair, the first found wrong element is stored in first pointer, while the next is stored in the second pointer.
e.g. The correct BST is below:
The inorder traversal is : 1 3 4 6 7 8 10 13 14
If we change the value 4 and 8: 1 3 8 6 7 4 10 13 14, when it goes to the node 6, now the pre->val = 8, check if pre
void getTwoNode(TreeNode *root,TreeNode *&n1, TreeNode*&n2, TreeNode*&pre){
if(!root ) return;
getTwoNode(root->left, n1, n2, pre);
if(pre && pre->val > root->val){
n2 = root;
if(n1==NULL)
n1 = pre;
else n2 = root;
}
pre = root;
getTwoNode(root->right,n1,n2,pre);
}
void recoverTree(TreeNode *root) {
TreeNode *n1=NULL, *n2=NULL, *pre = NULL;
if(!root) return;
getTwoNode(root,n1,n2,pre);
if(n1 && n2){
int temp = n1->val;
n1->val = n2->val;
n2->val = temp;
}
}
java
public class Solution {
TreeNode r1;
TreeNode r2;
TreeNode pre;
public void recoverTree(TreeNode root){
r1 = null;
r2 = null;
pre = null;
if(root == null) return;
inorderBST(root);
int temp = r1.val;
r1.val = r2.val;
r2.val = temp;
return;
}
public void inorderBST(TreeNode root){
if(root!=null){
inorderBST(root.left);
if(pre == null) pre = root;
else {
if(pre.val>root.val){
if(r1 == null) r1 = pre;
r2 = root;
}
pre = root;
}
inorderBST(root.right);
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.