编程练习-二叉树(求二叉树的高度)

题目:求二叉树的高度

解法:

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));
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值