首页 > 其他 > 详细

用递归求二叉树的高度

时间:2015-11-08 14:47:11      阅读:293      评论:0      收藏:0      [点我收藏+]
/// 用递归求二叉树的高度
/// 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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!