5.1.5 Recover Binary Sear Tree
来源:互联网 发布:云计算是什么 编辑:程序博客网 时间:2024/06/18 11:35
Notes: 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? Solution: 1. recursive solution. O(n) space. get inorder list first. 2. recursive solution. O(n) space. with only auxiliary two pointers. 3. Morris inorder traversal. O(1) space. with only auxiliary two pointers. */
解题思路:先对树进行中序遍历,将遍历的结果放在容器中,然后 找到两个乱序的数。
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: // first solution void recoverTree_1(TreeNode *root) { vector<TreeNode *> inorder; inorderTraversal(root, inorder); TreeNode *first = NULL, *second = NULL; for (int i = 1; i < inorder.size(); ++i) { if (inorder[i-1]->val < inorder[i]->val) continue; if (!first) first = inorder[i-1]; second = inorder[i]; } swap(first->val, second->val); } void inorderTraversal(TreeNode *root, vector<TreeNode *> &inorder) { if (!root) return; inorderTraversal(root->left, inorder); inorder.push_back(root); inorderTraversal(root->right, inorder); }
};
0 0
- 5.1.5 Recover Binary Sear Tree
- 5.1.7—二叉树的遍历—Recover Binary Sear Tree
- 5.3.5 Convert Sorted List to Binary Sear Tree
- 5.3.5—二叉查找树—Convert Sorted List to Binary Sear Tree
- 5.1.7 Recover Binary Search Tree
- 5.3.3—二叉查找树—Validate Binary Sear Tree
- 5.3.4—二叉查找树—Convert Sorted Array to Binary Sear 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
- verilog入门经验(一) always块使用
- 欢迎使用CSDN-markdown编辑器
- Android开发学习笔记:浅谈WebView
- UML建模
- Linux 内核--总线设备驱动模型(字符设备 && misc字符设备)
- 5.1.5 Recover Binary Sear Tree
- java中volatile关键字的含义解析及用途
- 使用jquery将图片放大
- Android中Handle的作用
- 《大话设计模式》读书笔记:策略模式+反射的Java实现
- yii2总结
- 十字链表
- Android系统及当前应用配置操作信息相关的常用API
- iframe跨域通信--html5.postmessage