博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode OJ 99. Recover Binary Search Tree
阅读量:4691 次
发布时间:2019-06-09

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

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?

 

 

Subscribe to see which companies asked this question

解答:

这道题其实就是利用有错位时,中序遍历过程中会出现前后两个节点值的大小关系不符合BST性质的情况出现,这样只要把两个点都标记下来就好了……不过这里要注意1,2,3,4,5和1,3,2,4,5这样的错误只会在遍历中只会遇到一次错误情况,而1,2,3,4,5和3,2,1,4,5这样的错误在遍历中就会产生两次错误情况,所以在每一次遇到错误情况时就要标记两个点,如果有第二次遇到错误情况只要更新其中的一个标记就好了,当然要注意null节点……这个是用Java写的,用C写我不会啊TAT

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {      TreeNode tmp = null, mis_node_1 = null, mis_node_2;            void find_mistake(TreeNode root) {          if(root==null)               return;          find_mistake(root.left);         if(tmp != null&&root.val < tmp.val){              if(null == mis_node_1)                  mis_node_1 = tmp;              mis_node_2 = root;          }          tmp = root;          find_mistake(root.right);      }      public void recoverTree(TreeNode root) {            find_mistake(root);          if(null != mis_node_1){              int tmp_val = mis_node_1.val;              mis_node_1.val = mis_node_2.val;              mis_node_2.val = tmp_val;          }      }  }

 

转载于:https://www.cnblogs.com/YuNanlong/p/6045403.html

你可能感兴趣的文章
iOS IM开发的一些开源、框架和教程等资料
查看>>
FansUnion:共同写博客计划终究还是“流产”了
查看>>
python 二维字典
查看>>
pip 警告!The default format will switch to columns in the future
查看>>
Arrays类学习笔记
查看>>
实验吧之【天下武功唯快不破】
查看>>
2019-3-25多线程的同步与互斥(互斥锁、条件变量、读写锁、自旋锁、信号量)...
查看>>
win7-64 mysql的安装
查看>>
dcm4chee 修改默认(0002,0013) ImplementationVersionName
查看>>
maven3在eclipse3.4.2中创建java web项目
查看>>
发布时间 sql语句
查看>>
黑马程序员 ExecuteReader执行查询
查看>>
记一些从数学和程序设计中体会到的思想
查看>>
题目1462:两船载物问题
查看>>
POJ 2378 Tree Cutting(树形DP,水)
查看>>
第二冲刺阶段个人博客5
查看>>
UVA 116 Unidirectional TSP (白书dp)
查看>>
第三方测速工具
查看>>
MySQL 网络访问连接
查看>>
在aws ec2上使用root用户登录
查看>>