Determine if two binary trees are equal

前端 未结 7 1987
臣服心动
臣服心动 2020-12-04 22:33

What would be the efficient algorithm to find if two given binary trees are equal - in structure and content?

7条回答
  •  自闭症患者
    2020-12-04 23:08

    I would write it as follows. The following code will work in most functional language, and even in python if your datatypes are hashable (e.g. not dictionaries or lists):

    • topological equality (same in structure, i.e. Tree(1,Tree(2,3))==Tree(Tree(2,3),1)):

      tree1==tree2 means set(tree1.children)==set(tree2.children)

    • ordered equality:

      tree1==tree2 means tree1.children==tree2.children

    (Tree.children is an ordered list of children)

    You don't need to handle the base cases (leaves), because equality has been defined for them already.

提交回复
热议问题