输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。例如输入整数22 和如下二元树
10
/ \
5 12
/ \ / \
{
intm_nValue; // valueof node
BinaryTreeNode *m_pLeft; // leftchildof node
BinaryTreeNode *m_pRight; //right childof node
10
/ \
5 12
/ \ / \
4 7 8 9
则打印出两条路径: 10, 12 和10, 5,7。二元树节点的数据结构定义为:
structBinaryTreeNode // a nodein thebinarytree
{
intm_nValue; // valueof node
BinaryTreeNode *m_pLeft; // leftchildof node
BinaryTreeNode *m_pRight; //right childof node
{
intm_nValue; // valueof node
BinaryTreeNode *m_pLeft; // leftchildof node
BinaryTreeNode *m_pRight; //right childof node
}
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef struct BiTreeNode
{
int data;
struct BiTreeNode *left;
struct BiTreeNode *right;
}BiTreeNode_T;
/*创建二叉树*/
BiTreeNode_T * CreateBSTree(int *data,int pos,int len)
{
BiTreeNode_T * tr;
if(pos>=len)
{
return NULL;
}
else
{
tr = (BiTreeNode_T *)malloc(sizeof(BiTreeNode_T));
tr->data = data[pos];
tr->left = CreateBSTree(data, 2*pos+1, len);
tr->right = CreateBSTree(data, 2*pos+2, len);
return tr;
}
}
//中序遍历二叉树
void InOrderTraverse(BiTreeNode_T *root)
{
if(root !=NULL)
{
InOrderTraverse(root->left);
if(NULL != root->left || NULL != root->right)
printf("%d not leaf node\n", root->data);
else
printf("%d \n",root->data);
InOrderTraverse(root->right);
}
}
//打印路径
void printPath(int path[], int top)
{
int i = 0;
for(i=0; i<top; i++)
printf("%d ", path[i]);
printf("\n");
}
//查找和为sum的路径,path数组存放路径的值,top代表每个可行的路径中的元素个数
void findPath(BiTreeNode_T *root, int sum, int top, int path[])
{
path[top++] = root->data;
sum -= root->data;
if (root->left == NULL && root->right==NULL)
{
/*叶子节点情况*/
if (sum == 0)
{
printPath(path, top);
top--;
sum += root->data;
}
}
else
{
/*非叶子节点情况*/
if(sum <= 0)
{
if(sum == 0)
printPath(path, top);
top--;
sum += root->data;
return;
}
if (root->left != NULL)
findPath(root->left, sum, top, path);
if (root->right!=NULL)
findPath(root->right, sum, top, path);
}
}
int main()
{
int data[]={10, 5, 12, 15, 7, 8, 9};
int len=sizeof(data)/sizeof(int);
BiTreeNode_T * root = CreateBSTree(data, 0, len);
InOrderTraverse(root);
printf("\n");
int sum=22;
int top=0;
int path[MAX] = {0};
printf("-------------------------------------\n");
findPath(root, sum, top, path);
return 0;
}
/*
打印
4
5 not leaf node
7
10 not leaf node
8
12 not leaf node
9
-------------------------------------
10 5 7
10 12
*/