题目描述:
两棵二叉树相等是指这两棵二叉树有着相同的结构,并且在相同位置上的结点有相同的值。判断两棵二叉树是否相等。
思路:
如果两棵二叉树 root1,root2相等,那么 root1 与root2 结点的值相同,同时它们的左右孩子也有着相同的结构,并且对应位置上结点的值相等,即 root1.data=root2.data,并且 root1 的左子树与 root2 的左子树相等,root1 的右子树与 root2 的右子树相等。根据这个条件,可以写出判断两个棵是否相等的递归算法。
算法性能分析:
此方法对两棵树只进行了一次遍历,所以时间复杂度为O(n);
此外,此方法没有申请额外的空间;
代码实现:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/1/23 21:59
# @Author : buu
# @Software: PyCharm
# @Blog :https://blog.csdn.net/weixin_44321080
class BiTNode:
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
def isEqual(root1, root2):
"""
判断两棵二叉树是否相等
:param root1: 一棵二叉树的根结点
:param root2: 另一棵二叉树的根结点
:return: True or False
"""
if root1 == None and root2 == None:
return True
if root1 == None and root2 != None:
return False
if root1 != None and root2 == None:
return False
if root1.data == root2.data:
return isEqual(root1.lchild, root2.lchild) and isEqual(root1.rchild, root2.rchild)
else:
return False
def constructTree():
"""
构造二叉树
:return:
"""
root = BiTNode()
node1 = BiTNode()
node2 = BiTNode()
node3 = BiTNode()
node4 = BiTNode()
root.data = 6
node1.data = 3
node2.data = -7
node3.data = -1
node4.data = 9
root.lchild = node1
root.rchild = node2
node1.lchild = node3
node1.rchild = node4
node2.lchild = node2.rchild = node3.rchild = node3.lchild = \
node4.lchild = node4.rchild = None
return root
if __name__ == '__main__':
root1 = constructTree()
root2 = constructTree()
equal = isEqual(root1, root2)
if equal:
print('true!')
else:
print('false!')
end