Diameter of Tree (in the form of parent pointer)

/***
Given a tree in the form of parent pointers of every node (for root assume parent pointer to be null), write code to find the diameter of tree.
IDEA: Space complexity O(1), time complexity(nlogn)

// mark non-leaf nodes
for each node do
  mark its direct parent node
end
// get max length
for each node do
  if node is marked then //non-leaf
    skip
  else // leaf
    visit all parent nodes until root and count the length
    keep the max length
  end
end
***/

#include<iostream>

using namespace std;

class node {
public:
       node(int);
       int data;
       bool visit;
       node *parent;
};

node :: node(int val) {
       data = val;
       visit = true;
       parent = nullptr;
}

int diameter_tree(node **n, int size) {

       int height = 0;
       // mark node to find leaf
       for(int i = 0; i<size; i++) {
       //Note: edge condition of parent
              if (n[i]->parent != nullptr)
                     n[i]->parent->visit = false;     
       }

       for(int i = 0; i<size; i++) {
              if(n[i]->visit) {
                     node *ptr = n[i];
                     int h = 0;
                     while(ptr != nullptr) {   
                           h++;
                           ptr = ptr->parent;  
                     }
                     if(h > height) height = h;
              }
       }     
       return height;      
}

void main() {
       node *n[7];
       for (int i = 0; i<7; i++)
              n[i] = new node(i+1);

       n[0]->parent = n[4];
       n[1]->parent = n[4];
       n[2]->parent = n[5];
       n[3]->parent = n[5];
       n[4]->parent = n[6];
       n[5]->parent = n[6];

       cout<<diameter_tree(n, 7)<<endl;


}

Comments

  1. The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).

    ReplyDelete

Post a Comment

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs