/// 用递归求二叉树的高度 /// Write a recursive function that returns the height of a binary tree. #include <cstdio> #include <iostream> #include <queue> #include <set> #include <cstdlib> #include <ctime> #include <fstream> #include <sstream> #include <cmath> #include <algorithm> using namespace std; class Node { private: int u; Node *left, *right; public: Node(int v, Node *Left = NULL, Node * Right = NULL); ~Node(); void addLeft(Node* Left = NULL); void addRight (Node * Right = NULL); int deep(); }; Node::Node(int v=0, Node *Left, Node *Right) { u = v; left = Left; right = Right; } Node::~Node() { if (left != NULL) delete left; if (right != NULL) delete right; left = right = NULL; } void Node::addLeft(Node * Left) { left = Left; } void Node::addRight(Node *Right) { right = Right; } int Node::deep() { if (this == NULL) return 0; return max( left->deep(), right->deep() ) + 1; } int main() { Node *p[9]; for (int i=0; i<8; i++) { p[i] = new Node(i); } p[0]->addLeft(p[1]); p[0]->addRight(p[2]); p[1]->addLeft(p[3]); p[1]->addRight(p[4]); p[2]->addLeft(p[5]); p[2]->addRight(p[6]); p[4]->addRight(p[7]); for (int i=0; i<8; i++) { cout<<"The hight of node "<<i<<" is "<<p[i]->deep()<<endl; } delete p[1]; return 0; }
原文:http://www.cnblogs.com/gufeiyang/p/4946990.html