LeetCode: Recover Binary Search Tree [099]
阿新 • • 發佈:2019-04-06
uri blog 第一次 str article ack ear ria com
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
【題目】
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; } };
LeetCode: Recover Binary Search Tree [099]