【题目】
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.
【题意】
给定的二叉搜索树中有两个节点的值错换了,找出这两个节点。恢复二叉搜索树。要求不适用额外的空间。
【思路】
中序遍历二叉树。一棵正常的二叉树中序遍历得到有序的序列,现有两个节点的值的调换了,则肯定是一个较大的值被放到了序列的前段。而较小的值被放到了序列的后段。节点的错换使得序列中出现了s[i-1]>s[i]的情况。假设错换的点正好是相邻的两个数,则s[i-1]>s[i]的情况仅仅出现一次。假设不相邻,则会出现两次,第一次出现是前者为错换的较大值节点,第二次出现时后者为错换的较小值节点。【代码】
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) {
stack<TreeNode*> st;
TreeNode* pointer=root;
TreeNode* prev=NULL;
TreeNode* nodeLarge=NULL;
TreeNode* nodeSmall=NULL;
while(pointer){st.push(pointer); pointer=pointer->left;}
while(!st.empty()){
TreeNode* cur = st.top();
st.pop();
if(prev && prev->val > cur->val){
if(nodeLarge==NULL || prev->val > nodeLarge->val) nodeLarge=prev;
if(nodeSmall==NULL || cur->val < nodeSmall->val) nodeSmall=cur;
}
prev=cur;
pointer=cur->right;
while(pointer){st.push(pointer); pointer=pointer->left;}
}
//替换两个节点的值
int temp=nodeLarge->val;
nodeLarge->val = nodeSmall->val;
nodeSmall->val = temp;
}
};