Hard-题目19:99. Recover Binary Search Tree

题目原文:
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(1)的空间复杂度把这两个节点恢复过来吗?
题目分析:
抓住二叉排序树的重要性质——中序遍历递增来解决此题。中序遍历这棵树,如果发现了gap(当前节点比前驱节点值小)则记录下来,要分两种情况,如果gap为1个,就是相邻的两个节点互换了,如果为两个,就是第一个gap的左节点和第二个gap的右节点互换了,分别记录一下互换的节点就好了,每次用一个类成员变量记录上次访问的节点,故空间复杂度为O(1).
源码:(language:java)

public class Solution {
    //private LinkedList<TreeNode> trace = new LinkedList<TreeNode>();
    private int gap = 0;
    private TreeNode lastvisit,node1,node2;
    public void recoverTree(TreeNode root) {
        if(root!=null) {
            inOrderVisit(root);
        }
        int temp = node1.val;
        node1.val = node2.val;
        node2.val = temp;
    }
    private void inOrderVisit(TreeNode root) {
        if(root!=null) {            
            inOrderVisit(root.left);
            if(lastvisit!=null && root.val<lastvisit.val) {
                if(gap == 0) 
                    node1 = lastvisit;  
                node2 = root;
                gap++;
            }
            lastvisit = root;
            inOrderVisit(root.right);
        }       
    }
}

成绩:
4ms,beats 42.88%,众数4ms,54.80%
Cmershen的碎碎念:
本学妹不是很清楚,二叉树递归算O(logn)空间复杂度吗?

你可能感兴趣的:(Hard-题目19:99. Recover Binary Search Tree)