【练习题】proj1 判断二叉树子树和是否为指定的值

 

 

 

 

#include <stdio.h>
#include <vector>
#include <list>
#include<iostream>
using namespace std;

struct BinaryTree{
    int weight;
    struct BinaryTree *left,*right;
};
int subtree_count(const struct BinaryTree *root,int m){
    int temp_val;
    static int count = 0;
    static int result=0;
    int left=0;
    int right=0;
    int flag=0;
    if(count == 0){
        flag =1;
    }
    count ++;
    if(root==NULL){
        return 0;
    }

    if(root->left!=NULL){
        left = subtree_count(root->left,m);
    }
    if(root->right!=NULL){
        right = subtree_count(root->right,m);
    }
    temp_val = left + right+root->weight;
    if(temp_val == m)
        result++;
    if(flag)
        return result;
    else
        return temp_val;
}


int main()
{
    int input=7;
    //cin >> input;
    BinaryTree *root1 = new BinaryTree;
    root1->weight=1;

    BinaryTree *root2 = new BinaryTree;
    root2->weight=2;
    BinaryTree *root3 = new BinaryTree;
    root3->weight=6;
    BinaryTree *root4 = new BinaryTree;
    root4->weight=1;
    BinaryTree *root5 = new BinaryTree;
    root5->weight=4;root4->right=NULL;

    root1->left=root2;
    root1->right=root3;
    root2->left=root4;
    root2->right=root5;
    root4->right=NULL;
    root4->left=NULL;
    root5->right=NULL;
    root5->left=NULL;
    root3->right=NULL;
    root3->left=NULL;
    cout <<subtree_count(root1,input);
    return 0;
}

 

转载于:https://www.cnblogs.com/ray5wang/p/9542574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值