检查树是否是二进制搜索树(BST)

编程入门 行业动态 更新时间:2024-10-23 15:17:15
本文介绍了检查树是否是二进制搜索树(BST)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试解决二进制搜索树问题,但是我无法通过所有测试用例.如果树是二进制搜索树,我需要返回true,否则,我需要返回false.谁能告诉我我在做什么错?

I am trying to solve a binary search tree problem, but I can't pass all of the test cases. I need to return true if the tree is a binary search tree, otherwise, I need to return false. Can anyone tell me what I am doing wrong?

''' class node: def __init__(self, data): self.data = data self.left = None self.right = None ''' def checkBST(root): if root.left == None and root.right == None: return True if root == None: return True if root.left != None: if root.left.data < root.data: return True else: return False if root.right != None: if root.right.data > root.data: return True else: return False return chckBST(root.left) and chckBST(root) and chckBST(root.right)

推荐答案

您的代码中有很多多余的if条件.您可以像这样简化它:

You've a lot of redundant if conditions in your code. You can simplify it like so:

def checkBST(root): if root == None or (root.left == None and root.right == None): return True elif root.right == None: return root.left.data < root.data and checkBST(root.left) elif root.left == None: return root.right.data >= root.data and checkBST(root.right) return checkBST(root.left) and checkBST(root.right)

首先,检查所有None条件. python中的短路保证如果第一个条件为False,则第二个条件将不被评估.这使您可以编写简洁的语句,例如return root.left.data < root.data and checkBST(root.left).

First, check for all the None conditions. Short circuiting in python guarantees that if the first condition is False, the second will not be evaluated. This allows you to write succinct statements such as return root.left.data < root.data and checkBST(root.left).

最后,如果左节点和右节点都不是None,请不再次调用checkBST(root).这导致无限递归.

Finally, in the event that neither left nor right nodes are None, do not call checkBST(root) again. This leads to infinite recursion.

更多推荐

检查树是否是二进制搜索树(BST)

本文发布于:2023-11-30 11:48:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:BST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!