二叉树遍历 前中后
#include <iostream>
using namespace std;
struct t{
int v;
struct t * left;
struct t * right;
};
void preorder(struct t *tree){
if (tree == NULL){
return;
}
cout << "i'm root " << tree->v << endl;
preorder(tree->left);
preorder(tree->right);
}
void backorder(struct t *tree){
if (tree == NULL){
return;
}
backorder(tree->left);
backorder(tree->right);
cout << "i'm root " << tree->v << endl;
}
void midorder(struct t *tree){
if (tree == NULL){
return;
}
midorder(tree->left);
cout << "i'm root " << tree->v << endl;
midorder(tree->right);
}
int main()
{
struct t trees[5]={};
cout << "hello world" << endl;
trees[0].v = 1;
trees[1].v = 3;
trees[2].v = 5;
trees[3].v = 7;
trees[4].v = 9;
for (int i=0; i<5; i++){
cout << trees[i].v << endl;
}
trees[0].left = &trees[1];
trees[0].right = &trees[2];
trees[1].left = &trees[3];
trees[1].right = &trees[4];
cout << "preorder" << endl;
preorder(trees);
cout << "backorder" << endl;
backorder(trees);
cout << "midorder" << endl;
midorder(trees);
return 0;
}
[root@ bigo]# g++ tree.cpp
[root@ bigo]#
[root@ bigo]#
[root@ bigo]# ./a.out
hello world
1
3
5
7
9
preorder
i'm root 1
i'm root 3
i'm root 7
i'm root 9
i'm root 5
backorder
i'm root 7
i'm root 9
i'm root 3
i'm root 5
i'm root 1
midorder
i'm root 7
i'm root 3
i'm root 9
i'm root 1
i'm root 5
[root@ bigo]#
我去滴滴面试,没答出这道题,遗憾。
还没有评论,来说两句吧...