首页 > 学院 > 开发设计 > 正文

99. Recover Binary Search Tree

2019-11-06 08:50:44
字体:
来源:转载
供稿:网友

问题描述 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); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表