加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

leetcode笔记:Recover Binary Search Tree

发布时间:2020-12-13 21:05:38 所属栏目:PHP教程 来源:网络整理
导读:1. 题目描写 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? 2. 题

1. 题目描写

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?

2. 题目分析

题目的大意是,在2叉排序树中有两个节点被交换了,要求把树恢复成2叉排序树。

1个最简单的办法是,中序遍历2叉树生成序列,然后对序列中排序毛病的进行调剂。最后再进行1次赋值操作。这类方法的空间复杂度为O(n)。

但是,题目中要求空间复杂度为常数,所以需要换1种方法。

递归中序遍历2叉树,设置1个prev指针,记录当前节点中序遍用时的前节点,如果当前节点大于prev节点的值,说明需要调剂次序。

3. 示例代码

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x),left(NULL),right(NULL) {} * }; */ class Solution { public: TreeNode *p,*q; TreeNode *prev; void recoverTree(TreeNode *root) { p=q=prev=NULL; inorder(root); swap(p->val,q->val); } void inorder(TreeNode *root) { if(root->left)inorder(root->left); if(prev!=NULL&&(prev->val>root->val)) { if(p==NULL)p=prev; q=root; } prev=root; if(root->right)inorder(root->right); } };

4. 小结

有1个技能是,若遍历全部序列进程中只出现了1次次序毛病,说明就是这两个相邻节点需要被交换。如果出现了两次次序毛病,那就需要交换这两个节点。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读