C++ 递归创建并遍历树
**
输入1 2 0 0 3 0 0
**
#include <bits/stdc++.h>
using namespace std;
typedef struct Tree{
int root;
Tree *left;
Tree *right;
}*BiTree;
void dfs(BiTree &tree) {
int n;
cin >> n;
if (n == 0) { tree = NULL; return;}
tree = new Tree;
tree->root = n;
dfs(tree->left);
dfs(tree->right);
}
// 根左右
void printfTree(BiTree tree) {
if(tree) {
cout << tree->root << " ";
printfTree(tree->left);
printfTree(tree->right);
}
}
int main(){
BiTree tree;
dfs(tree);
printfTree(tree);
system("Pause");
return 0;
}
例:
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
class Solution {
public:
int t[17] = {5,4,1,0,0,11,2,0,0,7,0,0,8,0,9,0,0}; // 输入的结点
int j = -1;
void buildTree(TreeNode* &root) {
j++;
if (t[j] == 0) {
root = NULL;
return;
}
root = new TreeNode;
root->val = t[j];
buildTree(root->left);
buildTree(root->right);
}
int main() {
Solution s;
TreeNode *root;
s.buildTree(root);
system("Pause");
return 0;
}