[LeetCode] 99. Recover Binary Search Tree Java

Posted BrookLearnData

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 99. Recover Binary Search Tree Java相关的知识,希望对你有一定的参考价值。

题目:

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?

题意及分析:一棵二叉搜索树的 两个点顺序错了,恢复它。找出顺序交换的两个点,交换点有两种情况:(1)一种是相邻两个点交换,这样只出现一次逆序(2)一种是不相邻两个点交换,出现两个逆序,交换的两个点分别为第一次逆序的第一个点和第二次逆序的第二个点,找到这两个点,然后交换。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode firstNode = null;
    TreeNode secondNode = null;

    TreeNode prevElement = new TreeNode(Integer.MIN_VALUE);

    public void recoverTree(TreeNode root) {                //一棵二叉搜索树的 两个点顺序错了,恢复它
        //找出顺序交换的两个点,交换点有两种情况:(1)一种是相邻两个点交换,这样只出现一次逆序(2)一种是不相邻两个点交换,出现两个逆序,交换的两个点分别为第一次逆序的第一个点和第二次逆序的第二个点,找到这两个点,然后交换
        traverse(root);

        int temp = firstNode.val;
        firstNode.val = secondNode.val;
        secondNode.val = temp;
    }

    public void traverse(TreeNode node){
        if(node == null)
            return;
        traverse(node.left);

        if(firstNode == null && prevElement.val >= node.val){       //逆序
            firstNode = prevElement;
        }
        if(firstNode!=null && prevElement.val>=node.val)
            secondNode = node;
        prevElement = node;

        traverse(node.right);
    }
}

 


以上是关于[LeetCode] 99. Recover Binary Search Tree Java的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 99. Recover Binary Search Tree

Leetcode 99. Recover Binary Search Tree

LeetCode OJ 99. Recover Binary Search Tree

leetcode 99 Recover Binary Search Tree ----- java

[LeetCode] 99. Recover Binary Search Tree Java

LeetCode-99-Recover Binary Search Tree