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

原创 2016年05月31日 23:33:33

题目原文:
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)空间复杂度吗?

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

leetcode 99. Recover Binary Search Tree 二叉树非递归遍历,利用stack和morris遍历

一开始觉得就按照二叉搜索树的构造规则由上至下,遇到违反大小规则的节点就直接交换这三个数的值就好了,知道遇到bad case:[3,null,2,null,1],产出结果[2,null,1,null,3...

LeetCode #99: Recover Binary Search Tree

Problem Statement(Source) Two elements of a binary search tree (BST) are swapped by mistake. Recover...

【LeetCode】99. Recover Binary Search Tree 分析、解法、注释、中序遍历、递归

99. Recover Binary Search Tree Total Accepted: 50739 Total Submissions: 192395 Difficulty: Hard...

LeetCode(99)Recover Binary Search Tree

题目如下: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without c...

LeetCode(99) Recover Binary Search Tree

题目Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changin...

[LeetCode]99.Recover Binary Search Tree

【题目】 Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without ...

[Leetcode] 99. Recover Binary Search Tree 解题报告

题目: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree with...

99. Recover Binary Search Tree

恢复二叉搜索树

leetCode 99: Recover Binary Search Tree

转自:http://blog.csdn.net/worldwindjp/article/details/21694179 Two elements of a binary search tree (...

Leetcode 99. Recover Binary Search Tree

99. Recover Binary Search Tree Total Accepted: 52531 Total Submissions: 196781 Difficulty: Ha...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)