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

[LeetCode] 99. Recover Binary Search Tree

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

[LeetCode] 99. Recover Binary Search Tree


Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.


一棵二叉搜索树,有两个节点换过来了,需要找出这两个节点,换回来。

我们发现,一棵完好的BST,它的中序遍历是一个有序的数组n。

从左往右找到第一个n[i-1] >n[i], n[i-1]为第一个错误节点。 从右往左找到第一个n[i+1] < n[i], n[i+1]为第二个错误节点,也就是从左往右找到最后一个n[i-1]>n[i], n[i]为第二个错误节点。


void helper(TreeNode* root, vector<TreeNode*>& wrong_root, TreeNode* &last_root) { if (root == NULL) return; helper(root->left, wrong_root, last_root); if (last_root && last_root->val > root->val) { // 左边第一个错的肯定是错误节点 if (wrong_root[0] == NULL){ wrong_root[0] = last_root; } // 右边最后一个错的垦丁是错误节点 if (wrong_root[0] != NULL) { wrong_root[1] = root; } } last_root = root; helper(root->right, wrong_root, last_root); } void recoverTree(TreeNode* root) { vector<TreeNode*> wrong_root(2, 0); TreeNode* last_root = NULL; helper(root, wrong_root, last_root); int tmp = wrong_root[0]->val; wrong_root[0]->val = wrong_root[1]->val; wrong_root[1]->val = tmp; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表