Recover Binary Search Tree
来源:互联网 发布:hmcl启动器 linux 编辑:程序博客网 时间:2024/06/15 23:32
http://blog.csdn.net/havenoidea/article/details/12869021
题意二叉查找树不合法,有两个节点的值被交换了,找出这两个节点并且不改变树的结构,使得二叉查找树合法,常数空间限制。
解题思路:中序遍历查找树会得到一个递增的数列。在中序遍历过程中,找出不符合递增条件的节点,然后交换它们的值。
class Solution {public: Solution(): pre(NULL), s1(NULL), s2(NULL){} void recoverTree(TreeNode *root) { if(!root) return; pre = NULL; s1 = NULL; s2 = NULL; findRecoverNode(root); if(s1 && s2) { swap(s1->val, s2->val); } }private: TreeNode *pre; TreeNode *s1; TreeNode *s2; void findRecoverNode(TreeNode *root) { if(!root) return; findRecoverNode(root->left); if(pre && pre->val > root-> val) { if(!s1) { s1 = pre; s2 = root; } else { s2 = root; } } pre = root; findRecoverNode(root->right); }};
0 0
- 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
- Recover Binary Search Tree
- Recover Binary Search Tree
- 内存管理初级
- SimpleCursorAdapter() 是 SimpleCursorAdapter 类的构造函数。
- 我的时间管理回顾——磨刀不误砍柴工
- 内存管理高级
- Spring AOP注解通过@Autowired,@Resource,@Qualifier,@PostConstruct,@PreDestroy注入属性的配置文件详解
- Recover Binary Search Tree
- 盛大员工积分体系的坍塌:为什么“打怪刷分”在现实里行不通
- 常见浏览器兼容问题及相关解决方法(chrome/IE/firefox)
- HHD Software Hex Editor Neo Ultimate Edition v6 10 02 5330-CRD
- 文章标题
- A and B and Team Training(贪心思想)
- html5中input的时间控件
- Spring HTTP Invoker使用介绍
- epoll