找出二叉树中和为某值的所有路径

本文介绍如何在二叉树中寻找从根节点出发,节点值之和等于给定目标值的路径。通过递归方法,当节点值等于目标值时返回路径,若节点值大于目标值则在左右子树中寻找剩余和,若节点值小于目标值则无法找到符合条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题是这样的,在一棵以root为根的树中,找出以root为起点的所有路径,要求路径中节点的值相加等于给定的数值。这个问题很简单,甚至于想都不用想就知道遍历树一遍就可以解决。

找出符合要求的路径,其实就是下面这个递归表达式:
1.求出以root为节点和等于v的路径;
2.如果root->value等于v,那么找到一条路径,返回;
3.如果root->value大于v,那么就分别找出以root左右孩子为根的和等于v – root->value的路径;
4.如果root->value小于v,那么就不存在符合条件的路径。
代码表示如下。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

struct tree {
	int value;
	struct tree *lchild;
	struct tree *rchild;
};

struct tree *insert(struct tree *root, int value)
{
	if (root) {
		if (value < root->value) {
			root->lchild = insert(root->lchild, value);
		} else {
			root->rchild = insert(root->rchild, value);
		}
	} else {
		root = new struct tree;
		root->value = value;
		root->lchild = 0;
		root->rchild = 0;
	}
	return root;
}

void print_tree_prefix(struct tree *root, string pfx)
{
	if (root) {
		if (root->lchild) {
			cout << pfx << "|" << endl;
			if (root->rchild) {
				cout << pfx << "|-<L> " << root->lchild->value << endl;
				print_tree_prefix(root->lchild, pfx + "|     ");
		    	} else {
				cout << pfx << "`-<L> " << root->lchild->value << endl;
			}
		}
		if (root->rchild) {
		    cout << pfx << "|" << endl;
		    cout << pfx << "`-<R> " << root->rchild->value << endl;
		    print_tree_prefix(root->rchild, pfx + "      ");
		}
	}
}

void print_tree(struct tree *root)
{
	if (root) {
	    cout << root->value << endl;
	    print_tree_prefix(root, "");
	}
}

string itos(int i)
{
	string str;
	stringstream s;
	s << i;
	s >> str;
	return str;
}

void sum_prefix(struct tree *root, int v, string pfx)
{
	if (root) {
		if (v == root->value) {
			cout << pfx << root->value << endl;
		} else if (v > root->value) {
			v -= root->value;
			pfx += itos(root->value) + "+";
			sum_prefix(root->lchild, v, pfx);
			sum_prefix(root->rchild, v, pfx);
		}
	}
}

void sum(struct tree *root, int v)
{
	if (root) {
		sum_prefix(root, v, itos(v) + "=");
	}
}

int main()
{
	struct tree *root = 0;
	root = insert(root,  10);
	root = insert(root,   5);
	root = insert(root,   4);
	root = insert(root,   7);
	root = insert(root,  12);
	root = insert(root,  23);
	root = insert(root,   1);
	root = insert(root,   6);
	root = insert(root,   2);
	print_tree(root);
	sum(root, 22);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值