上篇咱们说到二叉树的一种建立方法及三种遍历方法的递归非递归算法。这篇换了一种新的建立方法,用先根遍历递归的思路建立二叉树,用递归的方法计算深度,用中根递归和非递归方法遍历整个二叉树。
BinaryTree.h
//二叉树的建立和遍历
#ifndef BINARYTREE_H_
#define BINARYTREE_H_
#include <iostream>
typedef int T;
struct Node
{
T data;
Node *lch;
Node *rch;
};
class BinaryTree
{
private:
Node *root;
Node *create_bt();
void inorder(Node *p);
int predepth(Node *t);
void destroy(Node *p);
int max(int x, int y);
public:
BinaryTree()
{
root=NULL;
}
~BinaryTree()
{
destroy(root);
}
void create();
void inorder()
{
inorder(root);
}
void inorderz();//中根非递归遍历
int predepth(){return predepth(root);}//求二叉树的深度递归函数
};
#endif
BinaryTree.cpp
#include "BinaryTree.h"
#include <iostream>
#inc