Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a loop in a binary tree

Tags:

binary-tree

How to find a loop in a binary tree? I am looking for a solution other than marking the visited nodes as visited or doing a address hashing. Any ideas?

like image 950
novice Avatar asked Jul 05 '12 20:07

novice


2 Answers

Suppose you have a binary tree but you don't trust it and you think it might be a graph, the general case will dictate to remember the visited nodes. It is, somewhat, the same algorithm to construct a minimum spanning tree from a graph and this means the space and time complexity will be an issue.

Another approach would be to consider the data you save in the tree. Consider you have numbers of hashes so you can compare.

A pseudocode would test for this conditions:

  1. Every node would have to have a maximum of 2 children and 1 parent (max 3 connections). More then 3 connections => not a binary tree.
  2. The parent must not be a child.
  3. If a node has two children, then the left child has a smaller value than the parent and the right child has a bigger value. So considering this, if a leaf, or inner node has as a child some node on a higher level (like parent's parent) you can determine a loop based on the values. If a child is a right node then it's value must be bigger then it's parent but if that child forms a loop, it means he is from the left part or the right part of the parent.

    3.a. So if it is from the left part then it's value is smaller than it's sibling. So => not a binary tree. The idea is somewhat the same for the other part.

Testing aside, in what form is the tree that you want to test? Remeber that every node has a pointer to it's parent. An this pointer points to a single parent. So depending of the format you tree is in, you can take advantage from this.

like image 185
amb Avatar answered Oct 16 '22 16:10

amb


As mentioned already: A tree does not (by definition) contain cycles (loops).

To test if your directed graph contains cycles (references to nodes already added to the tree) you can iterate trough the tree and add each node to a visited-list (or the hash of it if you rather prefer) and check each new node if it is in the list. Plenty of algorithms for cycle-detection in graphs are just a google-search away.

like image 24
mariusnn Avatar answered Oct 16 '22 16:10

mariusnn