判断一个二叉树是否是合法二叉树,并写出Python代码
时间: 2024-06-01 08:06:49 浏览: 15
判断一棵二叉树是否合法需要满足以下条件:
1. 左右子树都必须是合法的二叉树
2. 左子树的最大值小于当前节点的值
3. 右子树的最小值大于当前节点的值
以下是Python代码实现:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isValidBST(root: TreeNode) -> bool:
def helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
if node.val <= lower or node.val >= upper:
return False
if not helper(node.right, node.val, upper):
return False
if not helper(node.left, lower, node.val):
return False
return True
return helper(root)
```
相关问题
如何判断一个二叉树是否是合法二叉树?
一个合法的二叉树需要满足以下几个条件:
1. 每个节点最多有两个子节点。
2. 左子树和右子树都必须是合法的二叉树。
3. 左子树中所有节点的值都小于当前节点的值,右子树中所有节点的值都大于当前节点的值。
因此,判断一个二叉树是否合法可以通过递归实现。从根节点开始,递归判断左子树和右子树是否合法,同时判断当前节点的值是否大于左子树中所有节点的值,是否小于右子树中所有节点的值。如果满足以上条件,则这是一个合法的二叉树。
用Python代码实现判断两个二叉树是否相同,并有主代码
可以通过递归的方式判断两个二叉树是否相同,具体实现如下:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSameTree(p: TreeNode, q: TreeNode) -> bool:
# 如果两个节点均为 None,则认为相同
if not p and not q:
return True
# 如果只有一个节点为 None,则认为不相同
elif not p or not q:
return False
# 如果节点的值不相同,则认为不相同
elif p.val != q.val:
return False
# 递归判断左右子树是否相同
else:
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
```
主代码如下:
```python
if __name__ == '__main__':
# 构造两个二叉树
p = TreeNode(1, TreeNode(2), TreeNode(3))
q = TreeNode(1, TreeNode(2), TreeNode(3))
# 判断两个二叉树是否相同
print(isSameTree(p, q)) # True
p = TreeNode(1, TreeNode(2), None)
q = TreeNode(1, None, TreeNode(2))
# 判断两个二叉树是否相同
print(isSameTree(p, q)) # False
```
以上代码中,我们先构造了两个二叉树,然后分别调用 `isSameTree` 函数判断它们是否相同,最终输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)