Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
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: 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],布布扣,bubuko.com
LeetCode: Recover Binary Search Tree [099]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/28092393