您的位置:首页 > 职场人生

面试题 二叉树的前序遍历,中序遍历,后序遍历(递归实现)

2014-11-20 14:54 519 查看
前序遍历递归解法:

(1)如果二叉树为空,空操作

(2)如果二叉树不为空,访问根节点,前序遍历左子树,前序遍历右子树

中序遍历递归解法

(1)如果二叉树为空,空操作。

(2)如果二叉树不为空,中序遍历左子树,访问根节点,中序遍历右子树

后序遍历递归解法

(1)如果二叉树为空,空操作

(2)如果二叉树不为空,后序遍历左子树,后序遍历右子树,访问根节点

参考实现代码:

[/u1/yyang/study/algorithm/binarytree](203)yyang@dcmvrh12#cat binarytree.h
#include <stdio.h>
#include <stdlib.h>

typedef struct  BinaryTreeNode
{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;

}BTN;

BTN* CreateBTNode(int value)
{
BTN* btnode = new BinaryTreeNode();
if(btnode)
{
btnode->value = value;
btnode->left = NULL;
btnode->right = NULL;
}
return btnode;
}

void CreateBTree(BTN* root, BTN* left, BTN* right)
{
if(root)
{
root->left = left;
root->right =right;
}
}

void DeleteNode(BTN* root)
{
if(root == NULL)
return ;
if(root->left) DeleteNode(root->left);
if(root->right) DeleteNode(root->right);
delete root;
root = NULL;
}
cpp文件

[/u1/yyang/study/algorithm/binarytree] (208)yyang@dcmvrh12#cat rectranverse.cpp
#include "binarytree.h"

void preOrder(BTN* root)
{
if(root == NULL)
return;
printf(" %d ",root->value);
preOrder(root->left);
preOrder(root->right);
}

void  inOrder(BTN* root)
{
if(root == NULL)
return;
inOrder(root->left);
printf(" %d ",root->value);
inOrder(root->right);
}

void postOrder(BTN* root)
{
if(root == NULL)
return;
postOrder(root->left);
postOrder(root->right);
printf(" %d ",root->value);
}

int main()
{

//            1
//         /      \
//        2        3
//       /\         \
//      4  5         6
//         /
//        7
//create BTN*node
BTN* btnode1 = CreateBTNode(1);
BTN* btnode2 = CreateBTNode(2);
BTN* btnode3 = CreateBTNode(3);
BTN* btnode4 = CreateBTNode(4);
BTN* btnode5 = CreateBTNode(5);
BTN* btnode6 = CreateBTNode(6);
BTN* btnode7 = CreateBTNode(7);

CreateBTree(btnode1,btnode2,btnode3);
CreateBTree(btnode2,btnode4,btnode5);
CreateBTree(btnode3,NULL,btnode6);
CreateBTree(btnode5,btnode7,NULL);

printf("preOrder is :\n");
preOrder(btnode1);

printf("\ninOrder is :\n");
inOrder(btnode1);

printf("\npostOrder is :\n");
postOrder(btnode1);
printf("\n");
//free the node
DeleteNode(btnode1);
}
编译和运行结果:

[/u1/yyang/study/algorithm/binarytree](209)yyang@dcmvrh12#g++ rectranverse.cpp -o rectranverse
[/u1/yyang/study/algorithm/binarytree](210)yyang@dcmvrh12#./rectranverse
preOrder is :
1  2  4  5  7  3  6
inOrder is :
4  2  7  5  1  3  6
postOrder is :
4  7  5  2  6  3  1
结果正确。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐