因为树是递归定义的,所以用递归算法很方便。
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> using namespace std; struct Node { char data; Node *lchild; Node *rchild; }; void High(Node *T, int &h) { if (T == NULL) h = 0; else { int left_h; High(T->lchild, left_h); int right_h; High(T->rchild, right_h); h = 1 + max(left_h, right_h); } } Node *CreateBiTree(Node *&T) { // 算法6.4 // 按先序次序输入二叉树中结点的值(一个字符),空格字符表示空树, // 构造二叉链表表示的二叉树T。 char ch; cin >> ch; if (ch == '#') T = NULL; else { if (!(T = (Node *)malloc(sizeof(Node)))) return 0; T->data = ch; // 生成根结点 CreateBiTree(T->lchild); // 构造左子树 CreateBiTree(T->rchild); // 构造右子树 } return T; } // CreateBiTree void Free(Node *&T) { if (T == NULL) return; Free(T->lchild); // T->lchild = NULL; Free(T->rchild); // T->rchild = NULL; free(T); T = NULL; } int main(int argc, char **argv) { freopen("cin.txt", "r", stdin); Node *T = NULL; CreateBiTree(T); int height; High(T, height); cout << height << endl; Free(T); return 0; } /* cin.txt: A B C # # D E # G # # F # # # */
构造的树:
输出为5。