题目:求二叉树的高度
解法:
1、递归调用时将当前高度和已经取得的最大高度作为遍历时的context传入,遍历的过程中不断更新这两个context,最后输出遍历过程中获得的最大高度
2、二叉树的高度是其左子树或右子树中较高的一个子树的高度再加1,由此获得二叉树的高度
程序如下:
#include <stdio.h>
#include <stdlib.h>
template<typename T>
class BinaryTree {
private:
class TreeNode {
public:
TreeNode(const T& key) : value_(key), left_(NULL), right_(NULL) {}
T value_;
TreeNode* left_;
TreeNode* right_;
};
public:
enum TreeHightAlgorithm {
ALG1 = 1,
ALG2 = 2
};
BinaryTree() : root_(NULL) {}
int TreeHight(TreeHightAlgorithm algorithm) {
if (algorithm == ALG1) {
return TreeHight(root_);
} else if (algorithm == ALG2) {
int current_hight = 0;
int max_hight = 0;
TreeHight(root_, current_hight, max_hight);
return max_hight;
}
}
void Insert(const T& key) {
Insert(key, root_);
}
private:
TreeNode* root_;
int TreeHight(TreeNode* current, int& current_hight, int& max_hight) {
if (current) {
current_hight++;
if (current_hight > max_hight) {
max_hight = current_hight;
}
TreeHight(current->left_, current_hight, max_hight);
current_hight--;
current_hight++;
TreeHight(current->right_, current_hight, max_hight);
current_hight--;
}
}
int TreeHight(TreeNode* current) {
if (current) {
int left_hight = TreeHight(current->left_);
int right_hight = TreeHight(current->right_);
if (left_hight > right_hight) {
return left_hight + 1;
} else {
return right_hight + 1;
}
} else {
return 0;
}
}
void Insert(const T& key, TreeNode*& current) {
if (current) {
if (key >= current->value_) {
Insert(key, current->right_);
} else {
Insert(key, current->left_);
}
} else {
current = new TreeNode(key);
}
}
};
int main(int argc, char** argv) {
BinaryTree<int> my_tree;
const int kKeySize = 100000;
for (int i = 0; i < kKeySize; ++i) {
my_tree.Insert(rand());
}
printf("the hight of tree: %d\n", my_tree.TreeHight(BinaryTree<int>::ALG1));
printf("the hight of tree: %d\n", my_tree.TreeHight(BinaryTree<int>::ALG2));
}