zoukankan      html  css  js  c++  java
  • 99. 恢复二叉搜索树-中序遍历-困难

    问题描述

    二叉搜索树中的两个节点被错误地交换。

    请在不改变其结构的情况下,恢复这棵树。

    示例 1:

    输入: [1,3,null,null,2]

      1
      /
     3
     
      2

    输出: [3,1,null,null,2]

      3
      /
     1
     
      2
    示例 2:

    输入: [3,1,4,null,null,2]

    3
    /
    1 4
      /
      2

    输出: [2,1,4,null,null,3]

    2
    /
    1 4
      /
     3
    进阶:

    使用 O(n) 空间复杂度的解法很容易实现。
    你能想出一个只使用常数空间的解决方案吗?

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/recover-binary-search-tree

    解答

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    //中序遍历,将每一个node保存到list里面,然后对list中的逆序的node的值交换。
    class Solution {
        List<TreeNode> list;
        public void recoverTree(TreeNode root) {
            list = new ArrayList<TreeNode>();
            inorder(root);
            int x=-1,y=-1;
            for(int i=0;i<list.size()-1;i++){
                if(list.get(i).val > list.get(i+1).val){
                    if(x==-1){
                        x = i;
                        y = i+1;
                    }else y = i+1;
                }
            }
            if(x!=-1 && y!=-1){
                int temp = list.get(x).val;
                list.get(x).val = list.get(y).val;
                list.get(y).val = temp;
            }
        }
        public void inorder(TreeNode root){
            if(root == null)return;
            inorder(root.left);
            list.add(root);
            inorder(root.right);
        }
    }
  • 相关阅读:
    Object.wait()与Object.notify()的用法
    浅析 Java Thread.join()
    线程状态
    cpu分析简介
    Linux统计某文件夹下文件、文件夹的个数
    Quarta介绍
    初识Quartz(三)
    restful api的10个最佳实践
    request.getSession(true)和request.getSession(false)的区别
    div+css画一个小猪佩奇
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13298574.html
Copyright © 2011-2022 走看看