树——recover-binary-search-tree
来源:互联网 发布:java正则表达式分组 编辑:程序博客网 时间:2024/05/24 07:31
题目:
二叉搜索树BST中有两个结点的值互相放错了位置,找出并交换它们。
思路:若依据BST性质,使用ArrayList存储其中序遍历,可以很方便的找出题目要求的两个值,但是空间复杂度为O(n)。
这里有两种情况需要注意:
1.两个放错位置的结点相邻,如 中序遍历为:1,2,4,3,5. 则pre.val>cur.val的情况只发生了一次;
2.两个结点不相邻,如 1,4,3,2,5. 则pre.val>cur.val的情况发生了两次。
一个很精妙的方法如下:
public class Solution { private TreeNode first=null;//first和second存放需要交换的两个结点。 private TreeNode second=null; private TreeNode pre=null;//pre存放中序遍历的上一个结点. public void recoverTree(TreeNode root) { if(root == null) return; inOrder(root); if(first!=null&&second!=null) { int temp=first.val; first.val=second.val; second.val=temp; } } public void inOrder(TreeNode root) { if(root.left!=null) inOrder(root.left); if(pre!=null&&pre.val>root.val)//若pre.val>root.val只发生了一次,first和second存放该相邻两结点 { //若pre.val>root.val发生两次,second存放第二个结点。 if(first == null) { first=pre; } second=root; } pre=root; if(root.right!=null) inOrder(root.right); }
0 0
- 树——recover-binary-search-tree
- leetcode——Recover Binary Search Tree
- LeetCode99—Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- (4.1.23.12)自定义控件三部曲之动画篇(十)——联合动画的XML实现与使用示例
- 【Android】注解机制详解
- python基础31[常用模块介绍]
- Unity3D研究院之提取游戏资源的三个工具支持Unity5
- Python numpy函数hstack() vstack() stack() dstack() vsplit() concatenate()
- 树——recover-binary-search-tree
- 本地推送实例
- 跨服务器Session共享的四种方法
- 64. Minimum Path Sum
- [容器]STL之list容器详解
- 递减剔除数组元素算法
- Qt下 QString转char*
- 关于angularJS uibModalInstace Unknown provider报错问题
- Qt: 使用QML来创建界面