zoukankan      html  css  js  c++  java
  • [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);
        }
    }
  • 相关阅读:
    C++ template —— 模板基础(一)
    《C++标准程序库》笔记之四
    《C++标准程序库》笔记之三
    《C++标准程序库》笔记之二
    C++标准程序库笔记之一
    JAVA中JPA的主键自增长注解设置
    SVN中服务器地址变更
    JAVA中正则表达式常用的四个方法
    反编译class文件并重新编译的方法
    JAVA中文件与Byte数组相互转换的方法
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7941387.html
Copyright © 2011-2022 走看看