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

后端 未结 18 1375
既然无缘
既然无缘 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条回答
  •  Happy的楠姐
    2020-12-24 07:21

    This is a O(N) solution

    int fn(root, sum, *count)                                                                               
    {                                                                                                   
        if(root == NULL)                                                                                
            return 0;                                                                                                                                                                                       
        int left =  fn(root->left, sum, count);                                                         
    
        int right = fn(root->left, sum, count);                                                                                                                                                            
    
        if(left == sum)                                                                                 
            *count++;                                                                                   
    
        if(right == sum)                                                                                
            *count++;                                                                                   
    
        if((root->data + left + right) == sum)                                                          
            *count++;                                                                                   
    
        return (root->data + left + right);                                                             
    }
    

提交回复
热议问题