LeetCode OJ - Recover Binary Search Tree

修复被交换节点的二叉搜索树
本文介绍了一种解决二叉搜索树中两个节点被错误交换的问题的方法。通过中序遍历的方式找到错误节点,并进行修正,同时提供了一个常数空间复杂度的解决方案。

题目:

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?

解题思路:

中序遍历BST,在遍历过程中记录出现错误的节点。err_1是第一次发生pre_val > root_val的节点,err_2是最后一次发生pre_val > root_val的节点。最后交换err_1->val 和 err_2->val

代码:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode *err_1, *err_2;
13     TreeNode *pre;
14     
15     void find2Nodes(TreeNode *root) {
16         if (root == NULL) return;
17         
18         if (root->left != NULL) {
19             find2Nodes(root->left);
20         }
21         if (pre != NULL && pre->val >= root->val) {
22             if (err_1 == NULL) err_1 = pre;
23             err_2 = root;
24         }
25         pre = root;
26         if (root->right != NULL) {
27             find2Nodes(root->right);
28         }
29     }
30     
31     void recoverTree(TreeNode *root) {
32         if (root == NULL) return;
33         
34         err_1 = err_2 = pre = NULL;
35         
36         find2Nodes(root);
37         swap(err_1->val, err_2->val);
38     }
39 };

 

转载于:https://www.cnblogs.com/dongguangqing/p/3737265.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值