博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 99 Recover Binary Search Tree (python)
阅读量:4169 次
发布时间:2019-05-26

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

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.
分析:
正确的二叉树中序遍历应该是递增,而交换了两个节点后会导致有
0处(交换的2个节点的值相等)或1处(交换的2个节点相邻且其值不相等)或2处(交换的2个节点不相邻且其值不相等)某节点值小于其前一个节点的值,找出错误的节点,最后交换即可。
Python代码:

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def recoverTree(self, root):        """        :type root: TreeNode        :rtype: void Do not return anything, modify root in-place instead.        """        #为Solution类添加数据成员precursor,用于在中序遍历树的过程中,指向当前节点的前驱节点。        self.precursor=None         ''' precursor初始值必须指定为None,随着不断的递归调用recursive_left_root_right()函数,        precursor第一次被赋值指向二叉搜索树的最左节点(注意,不是最左叶节点。最左节点和最左叶节点可能不是同一个节点)'''                #为Solution类添加数据成员mistake1和mistake2,用于指向错误的两个节点        self.mistake1=None        self.mistake2=None        self.recursive_left_root_right(root) #调用相应函数,找到错误的节点        self.mistake1.val,self.mistake2.val=self.mistake2.val,self.mistake1.val #交换2个错误节点的值,使二叉搜索树恢复正常            def recursive_left_root_right(self,root):        if root==None:            return         self.recursive_left_root_right(root.left) #递归地中序遍历左子树                if self.precursor!=None and self.precursor.val>root.val:            if not self.mistake1:                self.mistake1,self.mistake2=self.precursor,root            else:                self.mistake2=root        self.precursor=root                self.recursive_left_root_right(root.right) #递归地中序遍历右子树

(完)

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

你可能感兴趣的文章
Yocto tips (3): Yocto 如何重新编译Linux内核与dtb,并放到deploy目录?
查看>>
Yocto tips (4): Yocto 如何确定(找到)一个包的名字
查看>>
start kernel 之后没有任何输出与uboot无法将bootargs传入内核的调查方法与解决之道
查看>>
Yocto tips (5): Yocto如何更改source code的下载与git clone地址
查看>>
Yocto tips (7): Yocto Bitbake的clean与cleanall以及cleansstate的区别
查看>>
Yocto tips (19): Yocto SDK Toolchian的使用
查看>>
Yocto i.MX6 (TQIMX6) (04) : 使用mjpg-streamer做一个WebCam Server
查看>>
Nexus 7 Cyanogenmod OS Compile and errors
查看>>
Yocto tips (20): Yocto中qemu模拟器的使用,以zynq Cortex-A9为例
查看>>
打造嵌入式ARM Linux防火墙:1. iptables基础
查看>>
4G模块SIMCOM7100 LTE在ARM Linux下使用PPPD上网
查看>>
为小米4与小米3 Mi3 Mi4编译Cyanogenmod 12.1与13.0 (CM12与CM13) 的步骤以及错误解决
查看>>
原生Android系统的第一次开机google验证的解决
查看>>
S5P4418与S5P6618的Android boot.img的解压与压缩, Sparse ext4文件系统
查看>>
【EVB-335X-II试用体验】 u-boot与kernel的编译以及本地repo的建立
查看>>
【EVB-335X-II试用体验】 上手试用与资源使用
查看>>
【EVB-335X-II试用体验】 Yocto环境的建立及Rootfs的构建与使用
查看>>
<<C++程序设计原理与实践>>粗读--chapter0 chapter1 chapter2
查看>>
<<C++程序设计原理与实践>>粗读--chapter3 chapter4 Chapter5
查看>>
<<C++程序设计原理与实践>>粗读 -- chapter8 Chapter9
查看>>