博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Recover Binary Search Tree leetcode java
阅读量:7105 次
发布时间:2019-06-28

本文共 1130 字,大约阅读时间需要 3 分钟。

题目

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?

 

题解

 解决方法是利用中序遍历找顺序不对的两个点,最后swap一下就好。

 因为这中间的错误是两个点进行了交换,所以就是大的跑前面来了,小的跑后面去了。

 所以在中序便利时,遇见的第一个顺序为抵减的两个node,大的那个肯定就是要被recovery的其中之一,要记录。

 另外一个,要遍历完整棵树,记录最后一个逆序的node。

 简单而言,第一个逆序点要记录,最后一个逆序点要记录,最后swap一下。

 因为Inorder用了递归来解决,所以为了能存储这两个逆序点,这里用了全局变量,用其他引用型遍历解决也可以。

 

代码如下:

 

 1 
public 
class Solution {
 2     TreeNode pre;
 3     TreeNode first;
 4     TreeNode second;
 5       
 6     
public 
void inorder(TreeNode root){  
 7         
if(root == 
null)  
 8             
return;  
 9 
10         inorder(root.left);  
11         
if(pre == 
null){  
12             pre = root;  
//
pre指针初始
13 
        }
else{  
14             
if(pre.val > root.val){  
15                 
if(first == 
null){  
16                     first = pre;
//
第一个逆序点
17 
                }  
18                 second = root;  
//
不断寻找最后一个逆序点
19 
            }  
20             pre = root;  
//
pre指针每次后移一位
21 
        }  
22         inorder(root.right);  
23     }  
24       
25     
public 
void recoverTree(TreeNode root) {  
26         pre = 
null;  
27         first = 
null;  
28         second = 
null;  
29         inorder(root);  
30         
if(first!=
null && second!=
null){   
31             
int tmp = first.val;  
32             first.val = second.val;  
33             second.val = tmp;  
34         }  
35     } 

转载地址:http://qtphl.baihongyu.com/

你可能感兴趣的文章
python正则提取特定标签内的字符
查看>>
转:Android屏幕适配经验谈
查看>>
jquery ajax get post 的使用方法汇总
查看>>
50个必备的实用jQuery代码段
查看>>
网站安装打包 修改app.config[六]
查看>>
git 安装使用
查看>>
hive 分区表、桶表和外部表
查看>>
eclipse查看java方法域
查看>>
Linux系统究竟我要怎样学?
查看>>
正在学习linux的我写一封信给十年后的自己
查看>>
利用scp 远程上传下载文件/文件夹
查看>>
Windows下无窗口后台运行程序: ShellExecute
查看>>
读《美丽新世界》
查看>>
UIScrollView实现图片循环滚动
查看>>
我的友情链接
查看>>
王垠:怎样写一个解释器
查看>>
解决unicodedecodeerror ascii codec can’t decode byte 0xd7 in position 9 ordinal not in range(128)...
查看>>
Redis和Memcached的区别
查看>>
CSS选择器种类及介绍
查看>>
struts2 + form 表单上传文件
查看>>