一. 题目描述
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?
二. 题目分析
题目的大意是,在二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。
一个最简单的办法是,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。这种方法的空间复杂度为O(n)。
但是,题目中要求空间复杂度为常数,所以需要换一种方法。
递归中序遍历二叉树,设置一个prev指针,记录当前节点中序遍历时的前节点,如果当前节点大于prev节点的值,说明需要调整次序。
三. 示例代码
/** * Definition for binary tree * struct TreeNode { *int val; *TreeNode *left; *TreeNode *right; *TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:TreeNode *p,*q;TreeNode *prev;void recoverTree(TreeNode *root){p=q=prev=NULL;inorder(root);swap(p->val,q->val);}void inorder(TreeNode *root){if(root->left)inorder(root->left);if(prev!=NULL&&(prev->val>root->val)){if(p==NULL)p=prev;q=root;}prev=root;if(root->right)inorder(root->right);}};
四. 小结
有一个技巧是,若遍历整个序列过程中只出现了一次次序错误,,说明就是这两个相邻节点需要被交换。如果出现了两次次序错误,那就需要交换这两个节点。
谦受益,满招损。