博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode刷题篇】leetcode99 恢复二叉搜索树
阅读量:1887 次
发布时间:2019-04-26

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

题目:给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。

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

在这里插入图片描述

在这里插入图片描述

解题思路一、对其中序遍历存储其所有结点的值,对其中的值进行遍历,存储器异常值,对树进行遍历,找到异常值,并进行替换。

public void recoverTree(TreeNode root) {
List
nums = new ArrayList<>(); inorder(root,nums); // 获取不正确的两个位置 int[] swapped = findTwoSwapped(nums); recover(root,2,swapped[0],swapped[1]); } // 中序遍历获取结果 public void inorder(TreeNode root,List
nums) {
if(root==null) {
return; } inorder(root.left,nums); nums.add(root.val); inorder(root.right,nums); } // 获得中序遍历不确定的两个位置 public int[] findTwoSwapped(List
nums) {
int n = nums.size(); int x = -1,y=-1;; for(int i=0;i

题解二、中序遍历的隐式遍历过程中寻找其异常值。

// 二叉搜索树的隐式恢复	public void recoverTree_2(TreeNode root) {
Stack
stack = new Stack<>(); TreeNode x = null, y = null, pred= null; while(!stack.isEmpty()||root!=null) {
while(root!=null) {
stack.push(root); root = root.left; } root = stack.pop(); if(pred!=null&&root.val

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

你可能感兴趣的文章
小程序页面排版样式例子
查看>>
IOC容器Unity 使用
查看>>
js给onclick赋值,传参数
查看>>
.net日历控件 Calendar选择多个日期
查看>>
RecyclerView Item 行高定义无效的BUG
查看>>
markdown发生HTML渲染组件出错的解决方案
查看>>
android ScrollView嵌套WebView高度为0的BUG
查看>>
android 混淆代码后 app 运行报错时, 如何精准定位报错位置
查看>>
android 定位并通过百度在线查询详细地址教程
查看>>
android TextView 首行缩进与部分文字改变颜色大小效果
查看>>
android app 优化启动体验, 不闪白屏并且快速展示 splash
查看>>
INSTALL_FAILED_NO_MATCHING_ABIS 解决方案
查看>>
android 把打好的 apk 包通过 adb 的方式安装到手机上
查看>>
Android Studio 依赖方式 implementation 与 compile 的区别
查看>>
区块链学习之路[持续更新]
查看>>
RecycleView-Java.lang.IllegalArgumentException: Called attach on a child which is not detached
查看>>
AI学习笔记 (一) 手写识别
查看>>
关于 AAPT2 error: check logs for details 一个特殊的情况 (๑ŐдŐ)b
查看>>
java.lang.UnsatisfiedLinkError ... couldn't find "xxx.so" 的原因以及解决方案
查看>>
golang 系列 (一) Hello,world!
查看>>