A tree is represented in a matrix form such that A[i,j] = 1 if j is the ancestor of i. Otherwise A[i,j] = 0. Given this construct a normal binary tree.
tree* foo(int** a,int n)
{
int idx=find_root(a,n);//find the row with all 0s
if(idx==-1) return null;
tree* root=new tree();
root->val=idx;
root->left=NULL;
root->right=NULL;
queue
q.push(root);
while(!q.empty())
{
tree* tmp=q.top();
q.pop();
int child[2];
int len;
len=find_child(a,tmp->val,child); //find the index with 1 on a[][tmp->val]
if(len>0)
{
tree* child=new tree();
child->val=child[len];
child->left=NULL;
child->right=NULL;
tmp->left=child;
q.push(child);
}
if(len>1)
{
tree* child=new tree();
child->val=child[len];
child->left=NULL;
child->right=NULL;
tmp->right=child;
q.push(child);
}
}
return root;
}
No comments:
Post a Comment