(递归)插入列表判断,其实和第三篇中的原理类似,都是利用搜索树中根序自然有序的性质。不同的是这次采用递归的方法,每次插入至多两个结点,且每个结点判断时要比较两次,失败则返回False,成功即插入列表再下一层。代码如下:
def charge(tree):
if not tree: #根为None,则True
return True
L = [float('-Inf'), tree.data, float('Inf')]
def fun(t):
index = L.index(t.data)
if t.left:
if t.left.data >=L[index] or t.left.data<=L[index-1]:
return False
L.insert(index,t.left.data)
fun(t.left)
if t.right:
if t.right.data <= L[index] or t.right.data>=L[index+1]:
return False
L.insert(index+1,t.right.data)
fun(t.right)
fun(tree)
return True
递归方法还是比较好理解的,复杂度也不错(O(n)),缺点是层数过多时有栈溢出风险。
本文介绍了一种基于递归的列表插入判断方法,利用搜索树的根序自然有序特性,通过递归方式每次最多插入两个节点,并进行双重判断确保正确性。

被折叠的 条评论
为什么被折叠?



