【練習題】proj1 判斷二叉樹子樹和是否為指定的值
阿新 • • 發佈:2018-08-27
urn http space str ret image binary res input
#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; }
【練習題】proj1 判斷二叉樹子樹和是否為指定的值