LeetCode Recover Binary Search Tree

来源:互联网 发布:js checkbox按钮 编辑:程序博客网 时间:2024/06/06 18:39
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?
http://oj.leetcode.com/problems/recover-binary-search-tree/

二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。
最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。
但这种方法要求n的空间复杂度,题目中要求空间复杂度为常数,所以需要换一种方法。
递归中序遍历二叉树,设置一个pre指针,记录当前节点中序遍历时的前节点,如果当前节点大于pre节点的值,说明需要调整次序。
有一个技巧是如果遍历整个序列过程中只出现了一次次序错误,说明就是这两个相邻节点需要被交换。如果出现了两次次序错误,那就需要交换这两个节点。

AC代码:
public class Solution {    TreeNode mistake1, mistake2;;    TreeNode pre;        void recursive_traversal(TreeNode root) {        if(root==null) {            return;        }        if(root.left!=null) {            recursive_traversal(root.left);        }        if(pre!=null&&root.val<pre.val) {            if(mistake1==null) {                mistake1 = pre;                mistake2 = root;            } else {                mistake2 = root;            }        }        pre = root;        if(root.right!=null) {            recursive_traversal(root.right);        }    }    public void recoverTree(TreeNode root) {        //pre必须设为null,通过遍历的时候设进去。因为是中序遍历,所以pre应该是深层叶子左子树的父节点。        recursive_traversal(root);        if(mistake1!=null&&mistake2!=null) {            int tmp = mistake1.val;            mistake1.val = mistake2.val;            mistake2.val = tmp;        }    }}



4 2