将所有子节点的值为x的所有父节点的值求和哦

Examples:
Input : Binary tree with x = 2:

    4        
   / \       
  2   5      
 / \ / \     
7  2 2  3    

Output : 11

    4        
   / \       
  2   5      
 / \ / \     
7  2 2  3    

The highlighted nodes (4, 2, 5) above
are the nodes having 2 as a child node.

// C++ implementation to find the sum of all 
// the parent nodes having child node x 
#include <bits/stdc++.h> 

using namespace std; 

// Node of a binary tree 
struct Node 
{ 
	int data; 
	Node *left, *right; 
}; 

// function to get a new node 
Node* getNode(int data) 
{ 
	// allocate memory for the node 
	Node *newNode = 
		(Node*)malloc(sizeof(Node)); 
	
	// put in the data	 
	newNode->data = data; 
	newNode->left = newNode->right = NULL; 
	return newNode;	 
} 

// function to find the sum of all the 
// parent nodes having child node x 
void sumOfParentOfX(Node* root, int& sum, int x) 
{ 
	// if root == NULL 
	if (!root) 
		return; 
	//当左右两节点有其中一个等于x的时候将父节点的值加到sum 
	if ((root->left && root->left->data == x) || 
		(root->right && root->right->data == x)) 
		sum += root->data; 
	
	//遍历递归左子树和右子树,找到下一个符合条件的父节点,加到sum 
	sumOfParentOfX(root->left, sum, x); 
	sumOfParentOfX(root->right, sum, x); 
	
} 

// utility function to find the sum of all 
// the parent nodes having child node x 
int sumOfParentOfXUtil(Node* root, int x) 
{ 
	int sum = 0; 
	sumOfParentOfX(root, sum, x); 
	
	// required sum of parent nodes 
	return sum; 
} 

// Driver program to test above 
int main() 
{ 
	// binary tree formation 
	Node *root = getNode(4);		 /*	 4	 */
	root->left = getNode(2);		 /*	 / \	 */
	root->right = getNode(5);		 /*	 2 5	 */
	root->left->left = getNode(7);	 /*	 / \ / \	 */
	root->left->right = getNode(2); /* 7 2 2 3 */
	root->right->left = getNode(2); 
	root->right->right = getNode(3); 
	
	int x = 2; 
	
	cout << "Sum = "
		<< sumOfParentOfXUtil(root, x); 
		
	return 0;	 
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值