求二叉树节点值的和

struct node
{
	node* left;
	node* right;
	int value;
	node(int v):value(v),left(nullptr),right(nullptr){}
};
int sum(const node* root)
{
	if (root != nullptr)
	{
		if (root->left == nullptr && root->right == nullptr)
		{
			return root->value;
		}
		int sum_left = 0;
		if (root->left != nullptr)
		{
			sum_left = sum(root->left);
		}
		int sum_right = 0;
		if (root->right != nullptr)
		{
			sum_right = sum(root->right);
		}
		return sum_left + sum_right+root->value;
	}
}

int main()
{
	
	node one(1), two(2), three(3), four(4), five(5),six(6),seven(7);
	one.left = &two;
	one.right = &three;
	two.left = &four;
	two.right = &five;
	three.right = &six;
	four.right = &seven;
	std::cout << sum(&one) << std::endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jiaojinlin/article/details/86633910