博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
99. Recover Binary Search Tree
阅读量:6006 次
发布时间:2019-06-20

本文共 2095 字,大约阅读时间需要 6 分钟。

99. 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?confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.OJ's Binary Tree Serialization:The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.Here's an example:   1  / \ 2   3    /   4    \     5The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

解析

  • 一种非递归且不使用栈,空间复杂度为O(1)的遍历方法
class Solution_99 {public:    void recoverTree(TreeNode* root) {        TreeNode* first = NULL, *second = NULL, *parenet = NULL;        TreeNode*cur, *pre; //中序遍历        cur = root;        while (cur)        {            if (cur->left==NULL)            {                if (parenet&&parenet->val>cur->val)                {                    if (!first)                    {                        first = parenet;                    }                    second = cur;                }                parenet = cur;                cur = cur->right;            }            else            {                pre = cur->left; //找到左子树的最右节点                while (pre->right&&pre->right!=cur)                {                    pre = pre->right;                }                if (!pre->right)                {                    pre->right = cur;                    cur = cur->left;                }                else                {                    pre->right = NULL; //恢复树结构                    if (parenet&&parenet->val > cur->val)                    {                        if (!first)                        {                            first = parenet;                        }                        second = cur;                    }                    parenet = cur;                    cur = cur->right;                }            }        }        if (first&&second)        {            swap(first->val, second->val);        }    }};

题目来源

转载地址:http://lmsmx.baihongyu.com/

你可能感兴趣的文章
制作ubuntu系统u盘镜像,以及安装
查看>>
JAVA多线程深度解析
查看>>
Kafka High Level Consumer 会丢失消息
查看>>
时间轴
查看>>
入坑vim之配置文件vimrc
查看>>
java 获取系统当前时间的方法
查看>>
Ubuntu 10.04升级git 到1.7.2或更高的可行方法
查看>>
MyBATIS(即iBATIS)问题集
查看>>
Linux下autoconf和automake使用
查看>>
UDP之socket编程
查看>>
Spring Security4实战与原理分析视频课程( 扩展+自定义)
查看>>
Centos6.5升级系统自带gcc4.4.7到gcc4.8.0
查看>>
redis安装与配置文件详解
查看>>
VMware安装失败 “Failed to create the requested registry key Key:installer Error:1021"
查看>>
虚拟化系列-VMware vSphere 5.1 VDP备份管理
查看>>
接口设计
查看>>
同步工具类 java.util.concurrent.CountDownLatch
查看>>
带动量因子的BP网络源码(C#实现)
查看>>
Skia深入分析9——延迟渲染和显示列表
查看>>
mmap函数实现共享内存
查看>>