算法,写代码

[easy][BST-Tree]669.Trim a Binar

2017-11-06  本文已影响0人  小双2510

原题:

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree
Screen Shot 2017-11-05 at 4.49.41 PM.png Screen Shot 2017-11-05 at 4.51.37 PM.png

所犯的错误:

开始21,28行没有做赋值给root,导致出错。root是作为对象传入给函数的,如果不将返回值赋值给root,那么原来的Root等于没有任何函数操作所带来的改变。

Screen Shot 2017-11-05 at 4.53.16 PM.png

开始第18,22都没有写elif ,只是写了if。由于root可能在上一个if语句中发生变化,导致符合下一个If的条件,又进入了下一个if,这样就发生了错误。必须采用elif将他们互斥。

开始没有写28,21行,而在函数最后的return中这样写:return self.trimBST(root,L,R),导致程序进入无限循环而溢出栈。

上一篇 下一篇

猜你喜欢

热点阅读