二叉树遍历 前中后

来源:互联网 发布:java五子棋毕业论文 编辑:程序博客网 时间:2024/06/11 04:29

这里写图片描述

#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 world13579preorderi'm root 1i'm root 3i'm root 7i'm root 9i'm root 5backorderi'm root 7i'm root 9i'm root 3i'm root 5i'm root 1midorderi'm root 7i'm root 3i'm root 9i'm root 1i'm root 5[root@ bigo]# 

我去滴滴面试,没答出这道题,遗憾。

0 0
原创粉丝点击