为二叉树创建祖先矩阵

时间:2012-09-30 19:20:04

标签: algorithm tree

     1
   /  \
  2    3
 / \   / \
4   5 6   7

对于给定的二叉树,我们需要创建一个矩阵a [7] [7] 满足祖先属性如[2] [1] = 1,因为1是2的祖先....

我通过使用额外的空间阵列来解决它......我提出的解决方案是

int a[n][n]={0};
void updatematrix(int a[][n],struct node *root,int temp[],int index){

if(root == NULL)
  return ;
int i;

for(i=0;i< index;i++)
  a[root->data][temp[i]]=1;
temp[index]=root->data;

updatematrix(a,root->left,temp,index+1);
updatematrix(a,root->right,temp,index+1);
}

我的解决方案有任何错误吗? 我们可以在这里做这个吗?(我的意思是不使用临时数组)

1 个答案:

答案 0 :(得分:0)

temp包含从根到当前节点的路径,即从树上走到达当前节点时访问的节点集。

如果每个节点中都有一个父指针(但我猜不是),您可以按照这些指针向上走,然后遍历树以遍历与temp相同的节点集。但这会占用更多内存。

你也可以走几次树(伪代码):

def updatematrix(a,node):
  if node is null: return
  walkDown(a.data,node.left)
  walkDown(a.data,node.right)
  updatematrix(a,node.left)
  updatematrix(a,node.right)

def walkDown(data,node):
  if node is null: return
  a[node][data] = 1
  walkDown(data,node.left)
  walkDown(data,node.right)

相同的复杂性,但内存访问模式看起来缓存不太友好。