【问题标题】:How to check if a binary tree has mirror symmetery in its stucture (not values)如何检查二叉树的结构(不是值)是否具有镜像对称性
【发布时间】:2021-04-13 04:24:51
【问题描述】:

我被要求编写一个递归算法来检查二叉树的结构(不是值)是否具有镜像对称性。例如:

        1
       / \
      /   \
     /     \
     3      5
    / \    / \
    7  9  11 13
       /   \
      15   17

具有对称结构。我会很感激专家的眼睛来帮助我。提前致谢。 我知道如何检查值是否对称但不是实际结构。

【问题讨论】:

  • 不就是跟踪左右吗?
  • 一种方法是递归函数,签名为bool isMirrored(struct node *left, struct node *right),称为bool result = isMirrored(root->left, root->right);,总体思路是同时遍历左右子树的双DFS。
  • 你试过什么?添加当前方法/代码
  • 如果您知道如何检查值是否对称,只需假设每个节点上的值都为零并进行检查

标签: algorithm data-structures binary-tree mirror symmetric


【解决方案1】:

假设您有一个类 Node 具有 leftright 属性,则所需的函数在 Python 中可能如下所示:

def is_mirror(left, right):
    if left is None or right is None:  # Either one is None
        return left == right  # True when both are None
    return is_mirror(left.left, right.right) and is_mirror(left.right, right.left)

你可以这样称呼它:

# Create the example tree from the question:
tree = Node(1,
    Node(3,
        Node(7),
        Node(9,
            Node(15)
        )
    ),
    Node(5,
        Node(11,
            None,
            Node(17)
        ),
        Node(13)
    )
)

print(is_mirror(tree.left, tree.right))  # True

【讨论】:

    猜你喜欢
    • 2012-01-16
    • 2014-05-09
    • 1970-01-01
    • 2021-08-24
    • 2015-04-23
    • 2019-11-05
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    相关资源
    最近更新 更多