N-ary trees - symmetrical or not

Given an N-ary tree, find out if it is symmetrical along the line drawn through the root of the tree node. This is easy to do in the case of a binary tree. However for N-ary trees this seems difficult

+3
source share
4 answers

One way to think about this problem is to notice that a tree is symmetric if it is its own reflection, where the reflection of the tree is defined recursively:

  • Reflection of an empty tree itself.
  • Reflection of a tree with root r and children c1, c2, ..., cn is a tree with root r, and children reflect (cn), ..., reflect (c2), reflect (c1).

, , . :

  • .
  • r c1, c2,..., cn T, , r, n , c1..., cn .

, , . - O (n + d), n - ( ), d - ( tom ). d = O (n), O (n) . , O (n) , node .

:

1. The empty tree is symmetric.
2. A tree with n children is symmetric if the first and last children are mirrors, the second and penultimate children are mirrors, etc.

:

  • - .
  • r c1, c2,..., cn t d1, d2,..., dn iff r = t, c1 dn, c2 - dn-1 ..

, . , - O (d), d - . O (n), , , .

+6

(node ) . (node ) . . .

+2

. . 7... - ?

data Tree = Tree [Tree]
symmetrical (Tree ts) =
    (even n || symmetrical (ts !! m)) &&
    all mirror (zip (take m ts) (reverse $ drop (n - m) ts))
    where { n = length ts; m = n `div` 2 }
mirror (Tree xs, Tree ys) =
    length xs == length ys && all mirror (zip xs (reverse ys))
0

root node, . , . ( ), . , .

, , . , . !

0

Source: https://habr.com/ru/post/1734005/


All Articles