Recursion 返回最大值的树
为此,我编写了这段代码。也许这是错误的,所以请帮助我,因为我是这个领域的新手我想编写一个递归代码,比较两个叶节点(左和右)并将最大值返回给父节点nood递归函数应该如下所示:Recursion 返回最大值的树,recursion,data-structures,graph,tree,Recursion,Data Structures,Graph,Tree,为此,我编写了这段代码。也许这是错误的,所以请帮助我,因为我是这个领域的新手我想编写一个递归代码,比较两个叶节点(左和右)并将最大值返回给父节点nood递归函数应该如下所示: 50 / \ 30 70 (( which should return 50+70=120 )) int MyFunction(struct node *root){ str
50
/ \
30 70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
struct node *ptr=root;
int leftsum=0;
int rightsum=0;
if(ptr==NULL){
return;
}
else{
MyFunction(ptr->left);
leftsum=leftsum+ptr->key;
MyFunctipn(ptr->right);
rightsum=rightsum+ptr->key;
return (root->key+max(leftsum,rightsum));
}
}
完整代码:
int getMaxPath(Node* root){
// base case, We traveled beyond a leaf
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
// get the max current nodes left and right children
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
// return sum of current node value and the maximum from two paths starting with its two child nodes
return root->value + std::max(lsum,rsum);
}
#包括
结构节点{
int值;
节点*左;
节点*右;
节点(int-val){
值=val;
左=空;
右=空;
}
};
//创建一棵树并返回指向其根的指针
节点*buildTree1(){
/*按如下方式构建树:
50
/ \
30 70
*/
节点*根=新节点(50);
根->左=新节点(30);
根->右=新节点(70);
}
int getMaxPath(节点*根){
if(root==NULL){
//0对我们的答案没有任何贡献
返回0;
}
int lsum=getMaxPath(根->左);
int rsum=getMaxPath(根->右);
返回根->值+std::max(lsum,rsum);
}
int main(){
使用名称空间std;
Node*root=buildTree1();
int ans=getMaxPath(根);
如果它是重复的,你为什么要回答它?我回答了完全相似的问题,所以我只是举了一面旗子。我没有投反对票。
#include <iostream>
struct Node{
int value;
Node* left;
Node* right;
Node(int val){
value = val;
left = NULL;
right = NULL;
}
};
// make a tree and return a pointer to it's root
Node* buildTree1(){
/* Build tree like this:
50
/ \
30 70
*/
Node* root= new Node(50);
root->left = new Node(30);
root->right = new Node(70);
}
int getMaxPath(Node* root){
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
return root->value + std::max(lsum,rsum);
}
int main() {
using namespace std;
Node* root = buildTree1();
int ans = getMaxPath(root);
cout<< ans <<endl;
return 0;
}
int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+max(lvalue,rvalue);
}
int max(int r,int j)
{
if(r>j)
return r;
else
return j;
}