• [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);
        }
    }
  • 相关阅读:
    nginx php-fpm 输出php错误日志
    图解phpstorm常用快捷键
    Mysq性能分析 —— Genral log(普通日志)与 Slow log(慢速日式)
    Mac Terminal
    Git安装与配置
    Linux ulimit
    tcpdump
    Linux 基础
    TCP
    HTTP
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7941387.html
Copyright © 2020-2023  润新知