Function that determines the validity of a binary tree by checking if there are loops

半城伤御伤魂 提交于 2021-01-27 19:37:17

问题


I have to complete the function

bool HasLoop(Node* root)
{    
}

which determines the validity of a binary tree by checking if it has any loops.

So an Example:

Valid:
  X1
 /  \
X4   X5
 \    \
  X3   X7

Invalid:
  X1
 /  \
X4   X5
 \  /  \
  X3   X7

My idea is to mark each node we traverse as visited, and if we come across a visited node again, we would know a loop exists. But most of the examples involve sets, and our class hasn't gone over that yet. How do I proceed?

EDIT: WHAT I CAME UP WITH:

struct Node
{
int data;
struct node *left; 
struct node *right;
bool visited = false;
};

bool HasLoop(Node* root)
{    
  if(root==nullptr)
return;

if(root->visited)
return true;

if(!root->visited)
{
    root->visited = true;
    hasALoop(root->left);
    hasALoop(root->right);
}
return false;


}

回答1:


This can be done by simple traversal of the tree, by using a visited flag attribute (basically a bool member variable).

First you have a traversal where you clear the visited flag. Then you do a second traversal checking if the visited flag have been set for the node. If it haven't then you set it, else you report a loop.

In pseudo-code it could look something like this:

void check_loop(tree_node* const root)
{
    if (root->visited)
    {
        // You have a loop, report it
    }
    else
    {
        root->visited = true;

        // Traverse to children
        if (root->left)
        {
            check_loop(root->left);
        }

        if (root->right)
        {
            check_loop(root->right);
        }
    }
}

In my example above, the sub-tree traversal stops once you found a loop.

This will check all nodes in the tree, interior as well as leaf nodes, and also catches complicated loops and not only direct ones as you show.




回答2:


You can implement a similar function to the one I did in a recent contest

bool vis[100000] = {false};
int flag = 0;

void HasLoop(Node* root)
{    

if(root==NULL)
    return;

if(vis[root->data]==false)
    vis[root->data]=true;
else
    flag = 1; // This means it is already visited so set flag = 1


HasLoop(root->left);
HasLoop(root->right);

return;
}

Though this function works only if you don't have repeated data value in the tree. If you have it, then you can change structure of your tree so that every node has a unique id or index value and can check that in your vis array.



来源:https://stackoverflow.com/questions/61315707/function-that-determines-the-validity-of-a-binary-tree-by-checking-if-there-are

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!