99. Recover Binary Search Tree
来源:互联网 发布:托福阅读满分 知乎 编辑:程序博客网 时间:2024/06/04 19:36
问题描述
wo 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?
Subscribe to see which companies asked this question.解决思路
使用inorder遍历的办法,因为在二叉查询树时,inorder遍历会满足遍历到的节点是有序的,而此时为升序,所以我们只要找到两个不满足pre->val < cur->val的节点就可以了。代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* first=NULL; TreeNode* second=NULL; TreeNode* pre = new TreeNode(INT_MIN); void recoverTree(TreeNode* root) { helper(root); int tmp = first->val; first->val = second->val; second->val = tmp; } void helper(TreeNode* root) { if (root == NULL) return; helper(root->left); if (!first && pre->val >= root->val) first = pre; if (first && pre->val >= root->val) {second = root; } pre = root; helper(root->right); }};
0 0
- 99.Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- 99. Recover Binary Search Tree
- PAT甲级1054. The Dominant Color (20)
- C陷阱与缺陷(二)
- 欢迎使用CSDN-markdown编辑器
- Python 中遇到的小问题
- JSON基础知识
- 99. Recover Binary Search Tree
- Maven resources plugin 损坏二进制数据
- XMPP协议详解
- 最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
- 全面了解 Nginx 主要应用场景
- Permutations
- [bzoj2534]Uva10829L-gap字符串
- 二叉树2(二叉查找树的插入、查找、删除、遍历)
- java.lang.ClassNotFoundException:com.mysql.jdbc.Driver