Recover Binary Search Tree
来源:互联网 发布:class转java工具 编辑:程序博客网 时间:2024/06/06 09:20
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?
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:void recoverTree(TreeNode *root) {TreeNode *p1 = NULL, *p2 = NULL, *pre = NULL;travel(root, pre, p1, p2);if (p1 && p2) {int temp = p1->val;p1->val = p2->val;p2->val = temp;}}void travel(TreeNode *root, TreeNode *&pre, TreeNode *&p1, TreeNode *&p2) {if (root == NULL)return;travel(root->left, pre, p1, p2);if (pre && root->val < pre->val) {if (!p1) {p1 = pre;p2 = root;}else {p2 = root;}}pre = root;travel(root->right, pre, p1, p2);}};
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
- 关于Eclipse创建Android项目时,会多出一个appcompat_v7的问题
- 五、pl/sql块
- 异常处理
- 八、开发函数
- 网络协议基本常识
- Recover Binary Search Tree
- 四、属性数据类型
- 六、游标
- 开始编程 Day 1
- 【C++ Primer】 神秘的 sizeof(union) 、sizeof(struct) 和内存对齐技术
- 回调函数
- Php面向对象 – 继承和重写
- 三、子查询、伪劣和常用函数
- awk的学习