您的位置:首页 > 理论基础 > 数据结构算法

在二元树中找出和为某一值的所有路径-数据结构

2015-12-29 09:45 525 查看

描述:

   输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。

打印出和与输入整数相等的所有路径。

例如输入整数22 和如下二元树

          10

        / \

       5 12

      / \

     4  7

则打印出两条路径:10, 12 和10, 5, 7。

思路:

1、当访问到某一节点时,把该结点的值添加到当前和变量,且把该结点压入栈中。

2、若结点为叶子结点,且当前和变量等于期望的和,则打印栈中的结点值,即为所需的路径。

3、若结点不是叶子结点,继续访问它的左孩子结点,访问它的右孩子结点。

4、删除该结点。包括从当前和变量中减去结点值,从栈中弹出结点值。此时,已回到父结点。

程序中的栈,利用STL中的vector,这样简化了编码工作。

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <iostream>

using namespace std;

typedef struct _BSTNode
{
int data;
struct _BSTNode *lchild;
struct _BSTNode *rchild;
}BSTNode;

static int InsertBSTNode(BSTNode *&node, int data)
{
BSTNode *tmp = NULL;

if(NULL == node)
{
tmp = (BSTNode *)malloc(sizeof(BSTNode));
if(NULL == tmp)
{
printf("Malloc Error\n");
return 0;
}
tmp->data = data;
tmp->lchild = tmp->rchild = NULL;
node = tmp;
return 1;
}
//create left or right node
if(node->data > data)
{
InsertBSTNode(node->lchild, data);
}
else
{
InsertBSTNode(node->rchild, data);
}
return 1;
}

//非递归写法
static void FindPath(BSTNode *node, int number)
{
BSTNode *p = node;
std::stack<BSTNode *> s;
std::vector<int> path;
long current_sum = 0;
vector<int>::iterator iter;

while(p || !s.empty())
{
if(p != NULL)
{
s.push(p);
path.push_back(p->data);
current_sum += p->data;
p = p->lchild;
}
else
{
p = s.top();
//printf("%d\n", p->data);
if(p->rchild == NULL && current_sum == number)
{
for(iter = path.begin(); iter != path.end(); ++iter)
{
printf("%d ", *iter);
}
putchar('\n');
}
if(p->rchild == NULL)
{
current_sum -= p->data;
path.pop_back();
}
s.pop();
p = p->rchild;
}
}
}

//递归写法,中序遍历
static void FindPathRecursive(BSTNode *node, std::vector<int> &path, int number, int ¤t_sum)
{
if(node != NULL)
{
path.push_back(node->data);
current_sum += node->data;

FindPathRecursive(node->lchild, path, number, current_sum);

//printf("current_sum = %d,%d\n", current_sum, node->data);
if(node->rchild == NULL && number == current_sum)
{
vector<int>::iterator iter;
for(iter = path.begin(); iter != path.end(); ++iter)
{
printf("%d ", *iter);
}
putchar('\n');
}
if(node->rchild == NULL)
{
current_sum -= node->data;
path.pop_back();
}
FindPathRecursive(node->rchild, path, number, current_sum);
}
}

int main()
{
int number = 0;
BSTNode *root = NULL;
int current_sum=0;
//Create Binary Squence Tree
InsertBSTNode(root, 10);
InsertBSTNode(root, 12);
InsertBSTNode(root, 5);
InsertBSTNode(root, 7);
InsertBSTNode(root, 4);
//number
scanf("%d", &number);
FindPath(root, number);
//recursive
std::vector<int> path;
FindPathRecursive(root, path, number, current_sum);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构