面试题25二叉树中和为某一值的路径

来源:互联网 发布:梦龙软件视频教程 编辑:程序博客网 时间:2024/05/16 02:00


面试题25二叉树中和为某一值的路径 

思路:设立一个vector<int>Path 记录路径,定义一个static int sum 累加和。先序遍历二叉树一直累加根结点到叶子结点的值,当结点是叶子结点同时和为指定值时输出路径


#include<iostream>#include<cstdio>#include<cstdlib>#include<stack>#include<queue>#include<vector>using namespace std;  //面试题25二叉树中和为某一值的路径 思路:设立一个vector<int>Path 记录路径,定义一个static int sum 累加和。先序遍历二叉树一直累加根结点到叶子结点的值,当结点是叶子结点同时和为指定值时输出路径typedef struct BinaryTreeNode{    int data;BinaryTreeNode *left,*right;}BinaryTreeNode;void FindPath(BinaryTreeNode*pRoot,int expectedSum,vector<int>&Path){    if(pRoot==NULL){    return ;}static int sum=0;sum+=pRoot->data;Path.push_back(pRoot->data);bool IsLeaf=(pRoot->left==NULL)&&(pRoot->right==NULL);if(IsLeaf&&(sum==expectedSum))//节点为叶子结点同时路径和为指定值{    vector<int>::iterator iter;cout<<"值为"<<expectedSum<<"的路径为: ";for(iter=Path.begin();iter!=Path.end();iter++){     printf("%d\t",*iter);}printf("\n");}if(pRoot->left!=NULL){   FindPath(pRoot->left,expectedSum,Path);}if(pRoot->right!=NULL){    FindPath(pRoot->right,expectedSum,Path);}sum-=pRoot->data;//此处勿忘Path.pop_back();//此处勿忘}void CreateBinaryTree(BinaryTreeNode**pRoot)//从控制台中读入字符串  字符之间用逗号隔开  {      int  ch;      scanf("%d,",&ch);      if(ch==0)//最后遇到‘0’ 递归自然会结束好好想想就清楚了。      {          *pRoot=NULL;      }      else      {           *pRoot=new BinaryTreeNode;//先建立根节点          (*pRoot)->data=ch;          CreateBinaryTree(&((*pRoot)->left));//建立左子树          CreateBinaryTree(&((*pRoot)->right));//建立右子树      }  }  void PreOrder(BinaryTreeNode*pRoot){   if(pRoot==NULL)   {        return;   }   printf("%d\t",pRoot->data);   PreOrder(pRoot->left);   PreOrder(pRoot->right);}int main(){//根据先序先建立二叉树 10,5 ,4 # # 7 # # 12 # #;参考书上p143  页的的树/*                    10 5      12   4   7*/BinaryTreeNode *pRoot=NULL;cout<<"请输入先序遍历:"<<endl;CreateBinaryTree(&pRoot);     cout<<"先序遍历为:"<<endl;PreOrder(pRoot);cout<<endl;vector<int> path;FindPath(pRoot,22,path);   return 0;}


0 0
原创粉丝点击