Algorithm to print all paths with a given sum in a binary tree

后端 未结 18 1394
既然无缘
既然无缘 2020-12-24 07:04

The following is an interview question.

You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t

18条回答
  •  星月不相逢
    2020-12-24 07:17

    void printpath(int sum,int arr[],int level,struct node * root)
    {
      int tmp=sum,i;
      if(root == NULL)
      return;
      arr[level]=root->data;
      for(i=level;i>=0;i--)
      tmp-=arr[i];
      if(tmp == 0)
      print(arr,level,i+1);
      printpath(sum,arr,level+1,root->left);
      printpath(sum,arr,level+1,root->right);
    }
     void print(int arr[],int end,int start)
    {  
    
    int i;
    for(i=start;i<=end;i++)
    printf("%d ",arr[i]);
    printf("\n");
    }
    

    complexity(n logn) Space complexity(n)

提交回复
热议问题