对称的二叉树
发布日期:2021-05-07 08:26:13 浏览次数:14 分类:精选文章

本文共 1083 字,大约阅读时间需要 3 分钟。

对称的二叉树

【题目】:

实现一个函数,用来判断一颗二叉树是不是对称的。

【解题思路】:

  1. 定义一个对称前序遍历:根->右->左;
  2. 然后同时进行前序遍历和对称前序遍历,每遍历一个节点就进行判断。

示例代码:

#  define tree nodeclass TreeNode(object):    def __init__(self, val):        self.val = val        self.left = None        self.right = None#  create a treedef create_tree(nums, index):    if not nums:        return None    if index >= len(nums):        return None    root = TreeNode(nums[index])    root.left = create_tree(nums, index * 2 + 1)    root.right = create_tree(nums, index * 2 + 2)    return root#def is_symmetrical(root1, root2):    if root1 is None and root2 is None:        return True    if root1 is None or root2 is None:        return False    if root1.val != root2.val:        return False    return is_symmetrical(root1.left, root2.right) and is_symmetrical(root1.right, root2.left)# test# 1. create a symmetrical treeroot = create_tree([8, 6, 6, 5, 7, 7, 5], 0)print("symmetrical tree:", is_symmetrical(root, root))# 2. create a non-symmetrical treeroot = create_tree([8, 6, 9, 5, 7, 7, 5], 0)print("non-symmetrical tree:", is_symmetrical(root, root))

运行结果:

上一篇:二叉树的深度
下一篇:集成学习之Boosting

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月15日 01时57分38秒