read more on how binary tree is serialized on OJ. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traver"/>
经典指数          
原因
1006
浏览数
0
收藏数
 

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. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. Here's an example: 1 / \ 2 3 / 4 \ 5 The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

     举报   纠错  
 
切换
1 个答案
//得到查询二叉树的中序结构,查询二叉树的中序结构就是排序的顺序 class Solution { public: void recoverTree(TreeNode *root) { vector inorder; stack stack1; TreeNode *p = root; while(p || !stack1.empty()){ while(p){ stack1.push(p); p = p->left; } p = stack1.top(); stack1.pop(); inorder.push_back(p); p = p->right; } TreeNode *s, *b; for(int i=0; ival > inorder[i+1]->val) { b = inorder[i]; break; } } for(int i=inorder.size()-1; i>=1; i--){ if(inorder[i]->val < inorder[i-1]->val) { s = inorder[i]; break; } } int tmp = b->val; b->val = s->val; s->val = tmp; } };
 
切换
撰写答案
扫描后移动端查看本题