#include<bits/stdc++.h> using namespace std; string str; int len; struct treeNode{ char data; treeNode *L_child,*R_child; treeNode(char d){ data=d; } }; template<class T> class Tree{ public: Tree(){ root=NULL; } treeNode* createNode() { treeNode *t; if(len>=str.size()){ return NULL; } T data = str[len++]; if(data=='*'){ t=NULL; }else{ t=new treeNode(data); t->L_child=createNode(); t->R_child=createNode(); } return t; }; treeNode* getRoot(); int getAns(treeNode *root); void LRN(treeNode *root); private: treeNode *root; }; template<class T> treeNode* Tree<T>::getRoot() { return this->root; } template<class T> int Tree<T>::getAns(treeNode *root){ if(root==NULL) return 0; int ans = 0; if(root->L_child!=NULL&&root->R_child!=NULL){ ans=1; } return ans+getAns(root->L_child)+getAns(root->R_child); } int main() { while(cin>>str){ len=0; Tree<char> *tree = new Tree<char>(); treeNode *root = tree->getRoot(); root = tree->createNode(); cout<<tree->getAns(root)<<endl; } }
时间: 2024-04-21 14:27:38 浏览: 14
这段代码实现了一个二叉树的构建和求解:先通过输入的字符串构建一棵二叉树,然后统计二叉树中有多少个节点同时拥有左右子树(即度为2的节点),最后输出结果。具体实现过程为:
- 定义了一个 treeNode 结构体,其中包括节点的数据(char 类型)和左右子树的指针。
- 定义了一个 Tree 类,其中包括根节点的指针和三个成员函数:
- createNode():通过递归的方式,将输入的字符串构建成一棵二叉树。
- getRoot():获取根节点的指针。
- getAns():统计二叉树中有多少个节点同时拥有左右子树。
- 在主函数中,通过循环输入字符串,每次构建一棵二叉树并统计结果,最后输出结果。
相关问题
#include <bits/stdc++.h> using namespace std
这段代码是一个C++的头文件引用和命名空间的使用示例。具体来说,`#include <bits/stdc++.h>`是一个常用的头文件引用方式,它包含了C++标准库中的所有头文件。而`using namespace std`则是为了使用`std`命名空间中的标准库函数和对象,这样就可以直接使用`cout`、`cin`等标准输入输出流对象,而不需要写`std::cout`、`std::cin`。
这种写法虽然方便,但也存在一些问题。首先,包含了所有的标准库头文件可能会导致编译时间变长。其次,使用了`using namespace std`会将整个`std`命名空间中的所有标识符引入当前作用域,可能会导致命名冲突。因此,在实际开发中,建议根据需要只包含需要的头文件,并使用具体的命名空间来避免潜在的问题。
#include <bits/stdc++.h> using namespace std;
这个头文件是C++11标准引入的,它包含了所有标准库中的头文件。使用这个头文件可以方便地在一个地方包含所有需要的头文件,而不需要一个一个地包含。这个头文件通常只在竞赛中使用,因为它不是标准C++头文件,不保证在所有编译器中都能正常工作。
以下是一个使用这个头文件的示例,实现输入4个整数a、b、c、d,将它们倒序输出:
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
cout << d << ' ' << c << ' ' << b << ' ' << a << endl;
return 0;
}
```