在二元树中找出和为某一值的所有路径 题目(树的路径)

虽然不难,我却调了2个小时,

手太生

题目:

4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
       10                                         
      /                                           
     5    12                                      
    /                                           
   4        7
则打印出两条路径:10, 12和10, 5, 7。

 
 
 
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct Node
{
    int m;
    Node *left;
    Node *right;
    



};

Node* create(int a[],int lev,int len)
{
    Node *node;
    if(a[lev]==-1)
    {
      return NULL;
    }
    else
    {
        node=new Node;
        node->m=a[lev];
        node->left=NULL;
        node->right=NULL;
        if(2*lev+1<len)
        {
        node->left=create(a,2*lev+1,len);
        
        }
        if(2*lev+2<len)
        {
    node->right=create(a,2*lev+2,len);
        }
    
    }


    return node;

}


void dispalyAllPaht(Node *root,int a[],int len,int sum,int pathsum)

{
    if(root==NULL) return;
    if(root->left==NULL&&root->right==NULL&&sum+root->m==pathsum)
    {
            
        
        int sum=0;
     for(int i=0;i<len;i++)
     {
       cout<<a[i]<<"-->";
       sum+=a[i];
     }
     cout<<root->m<<endl;
    
    }
    else
    {
        a[len]=root->m;
        dispalyAllPaht(root->left,a,len+1,sum+a[len],pathsum);
        dispalyAllPaht(root->right,a,len+1,sum+a[len],pathsum);    
    
    
    }



}


int main()
{
    int arr[]={10,5,12,4,7};
    int len=sizeof(arr)/sizeof(int);
    Node *root=create(arr,0,len);
    //cout<<root->m;
    int a[10];
    //prorder(root);
    //disqueue(root);
    cout<<"和为22"<<"的路线如下"<<endl;    
   dispalyAllPaht(root,a,0,0,22);


    
    system("pause");
    return 0;


}
原文地址:https://www.cnblogs.com/hansongjiang/p/3720708.html