[leedcode 99] Recover Binary Search Tree
2015-07-16 23:03
721 查看
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?
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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode firstNode; TreeNode secondNode; TreeNode pre; public void recoverTree(TreeNode root) { //对于二叉搜索树来讲,中序遍历应该是递增的,本题要求O(1)空间,出发点就是中序遍历的变形 //在中序遍历的过程中,需要找到fisrtWrongNode和secondWrongNode,本题最主要的是,使用pre全局遍历, /*递归的时候使得pre=root,达到pre能够保存root前置节点的作用,通过比较root和pre的值,找到逆序对, 如果两个数相邻置换,则逆序对只有一个, 如果两个数不相邻,逆序对有两个,此时需要更新secondWrongNode*/ if(root==null) return; inOrder(root); swap(firstNode,secondNode); } public void inOrder(TreeNode root){ if(root==null) return; inOrder(root.left); /* if(pre!=null&&firstNode==null&&root.val<pre.val){ firstNode=pre; } if(pre!=null&&firstNode!=null&&root.val<pre.val){ secondNode=root; }可被下面一个if语句替换*/ if(pre!=null&&root.val<pre.val){ if(firstNode==null) firstNode=pre; secondNode=root; } pre=root; inOrder(root.right); } public void swap(TreeNode s1,TreeNode s2){ int temp=s1.val; s1.val=s2.val; s2.val=temp; } }
相关文章推荐
- Cisco IOS XR在VMware环境下如何增加物理接口
- C++之纯虚函数
- Objective-C学习笔记之SEL和@selector
- MyCnCart图片水印
- LeetCode Search a 2D Matrix(二分查找法)
- Memcache技术分享:介绍、使用、存储、算法、优化、命中率
- 屏幕适配
- POJ 1064 Cable master (二分 分数化整数)
- LOL
- 【西祠日志】【02】
- Java中equals和==的区别
- 2015071602 - 夏季养生
- C语言中结构体的声明方式
- 2.4 成员初始化列表
- 开放与封闭
- 2015071601 - 楼梯
- 输入两个字符串,从第一个字符串中删除第二个字符串中出现过的所有字符
- map 按照值排列
- 二分查找(模板)
- Redis数据类型--hash