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

来源:互联网 发布:中世纪2全面战争mac版 编辑:程序博客网 时间:2024/06/01 11:07
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12 和10, 5, 7。
分析:需对树进行深度遍历,记录深度遍历过程中走过的路径的值的和,走到叶子节点判断是否与输入一致,如一致则打印

struct BSTreeNode
{
   int value;
   BSTreeNode *left;
   BSTreeNode *right;       
}
void printpath(int path[],int length)
{
   for(int i=0;i<length;i++)
      cout<<path[i];     
}
//递归算法
void search(BSTreeNode *root,int sum,int top,int path[])
{
    path[top++]=root->value; //记录路径
    sum-=root->value;
    if(root->left==null && root->right==null)
       if(sum==0) printpath(path,top);
    else
    {
       if(root->left!=null) search(root->left,sum,top,path);
       if(root->right!=null) search(root->left,sum,top,path);   
    }    
    top--;  //消除上一路径
    sum-=root->value;
}
//非递归算法
void searchN(BSTreeNode *root,int sum,int top,int path[])
{
   Stack <BSTreeNode>s=new  Stack <BSTreeNode> ();
   while(root!=bull || !isempty())
   {
       while(root!=null)
       {
          path[top++]=root->value;
          sum-=root->value;  
          s.push(root);
          root=root->left;               
       }   
       if(!isempty)
       {
           root=s.pop();
           root=root->right;  
           if(root==null && sum==0)
           {
               printpath(path,top); 
               sum-=root->value; 
               top--;            
           }      
       }           
   } 
}
0 0
原创粉丝点击