Binary Trees question. Checking for similar shape

后端 未结 5 608
刺人心
刺人心 2021-01-06 06:49

Hi I\'m stuck doing this, not sure how to go about it.

If I have two binary trees, how would I check if the have the same shape? Data in the nodes doesn\'t matter, j

5条回答
  •  情歌与酒
    2021-01-06 07:44

    If I have two binary trees, how would I check if the have the same shape?

    You will be pleased to know that binary trees have an interesting property: they can be represented as arrays. Simply convert each tree to one of these arrays and compare the array contents. Blank cells correspond to left or right children that don't exist, defining the structure of the tree. You want to iterate over both arrays and make sure that each blank cell encountered in one array appears in the other array; this is O(n).

    Of course, if the arrays are different sizes, you don't have to do any work at all, since trees with different numbers of nodes can't possibly have identical structure. From there, you're all done.

提交回复
热议问题