Leetcode Recover Binary Tree
2015-10-17 21:13
302 查看
*
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? confused what “{1,#,2,3}” means? > read more
on how binary tree is serialized on OJ.
*
代码基本大同小异,上次 通过是1年5个月前的事,前两天笔试出了这个题又不会做了,拿出来复习一下。
1。首先碰见搜索二叉树肯定是中序遍历,中序遍历后是个有序有序,所以可以找出哪些节点有冲突。
在找的时候,需要加一个pre指针。 这个用法还挺实用的,把一颗二叉树转换成循环链表 也要加上这个pre指针。
2。就是找到冲突节点时候怎么处理。
假设只有两个冲突节点,如A1,A2 那这两个就是我们所要求的值 。直接替换即可。
如果找到四个冲突节点。 A1 A2 B1 B2 满足 A1>A2 B1>B2 这四个节点中有两个节点的位置是冲突的是哪两个节点呢。
当时笔试就卡在这个地方了。 被破坏的两个节点肯定是A中一个,B中一个,假设A2是破坏的节点,那么A2要和B 中的节点交换,但是仍然小于A1,所以A2不是被破坏的节点,A1才是。 同理,B1如果是被破坏的节点,B1换到前面去 仍然比B2大,所以B2才是破坏的节点。。
所以判定 当有Pre 节点是 和pre节点比较值得大小,如果有冲突,看是第一对冲突节点和第二对冲突节点。只找到一对冲突节点,那就返回这一对,所以有
所以所以前写的代码还是有点问题的,当时不知道怎么过的。。。。
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? confused what “{1,#,2,3}” means? > read more
on how binary tree is serialized on OJ.
*
public class Solution { TreeNode pre; TreeNode first; TreeNode second; public void recoverTree(TreeNode root) { pre=null;first=null;second=null; inorder(root); if (first!=null){ if (second==null)second=pre; int tmp= first.val; first.val=second.val; second.val=tmp; } } public void inorder (TreeNode root){ if (root==null) return; if (root.left!=null) inorder(root.left); if (pre!=null){ if (first==null && pre.val>root.val) first=pre; else if(first!=null && root.val>first.val ) second=pre; if (first!=null && second!=null) return; } pre=root; if (root.right!=null) inorder(root.right); } }
代码基本大同小异,上次 通过是1年5个月前的事,前两天笔试出了这个题又不会做了,拿出来复习一下。
1。首先碰见搜索二叉树肯定是中序遍历,中序遍历后是个有序有序,所以可以找出哪些节点有冲突。
在找的时候,需要加一个pre指针。 这个用法还挺实用的,把一颗二叉树转换成循环链表 也要加上这个pre指针。
2。就是找到冲突节点时候怎么处理。
假设只有两个冲突节点,如A1,A2 那这两个就是我们所要求的值 。直接替换即可。
如果找到四个冲突节点。 A1 A2 B1 B2 满足 A1>A2 B1>B2 这四个节点中有两个节点的位置是冲突的是哪两个节点呢。
当时笔试就卡在这个地方了。 被破坏的两个节点肯定是A中一个,B中一个,假设A2是破坏的节点,那么A2要和B 中的节点交换,但是仍然小于A1,所以A2不是被破坏的节点,A1才是。 同理,B1如果是被破坏的节点,B1换到前面去 仍然比B2大,所以B2才是破坏的节点。。
所以判定 当有Pre 节点是 和pre节点比较值得大小,如果有冲突,看是第一对冲突节点和第二对冲突节点。只找到一对冲突节点,那就返回这一对,所以有
if(pre!=null && pre.val>root.val){ if(first==null){ //找到第一队冲突节点 first=pre; second=root; }else{ //直接确认第二个冲突节点是第二对的第二个。 second=root; }
所以所以前写的代码还是有点问题的,当时不知道怎么过的。。。。
相关文章推荐
- TdxAlertWindowManager右下角HINT显示控件
- 猜拳游戏的制作-使用if制作
- ZOJ 3767
- 汇编和反汇编的区别
- Python3学习笔记——基础的巩固
- 数组中求最大最小值
- simple introduction for pipe line
- Spring 通过配置向 Quartz定时任务 注入service
- pcduino里,Qt无法打开摄像头(调用了opencv)
- 三目运算符
- 好想哭
- Prime Query【ZOJ--3911】
- Chapter 5 Probabilistic Analysis and Randomized Algorithms
- 解决VMware vSphere Client与本机的鼠标无缝移出移入、剪贴板共享、共享文件夹等问题,实现虚拟机上虚拟硬件的驱动
- Kloxo面板无法登录出现500错误的解决方法
- hdu 2391 Filthy Rich
- 使用VS2013编译webkit
- 第三次作业 结对编程 (小神童数学测试系统)
- cisco 10条IOS管理命令
- android程序在华为手机调试时,Log不能捕获问题