Play with Tree

题目描述
Given a binary tree, your task is to get the height and size(number of nodes) of the tree.
The Node is defined as follows.

struct Node {
Node *lc, *rc;
char data;
};

Implement the following function.

void query(const Node *root, int &size, int &height)
{
// put your code here
}

提示
In this problem, we assume that the height of the tree with only one node is 1.
参考答案

#include <iostream>
#include "play.h"
using namespace std;

int getsize(const Node *root)
{
    if (root == NULL)
        return 0;
    return getsize(root->lc) + getsize(root->rc) + 1;
}

int getheight(const Node *root)
{
    if (root == NULL)
        return 0;
    int leftheight = getheight(root->lc) + 1;
    int rightheight = getheight(root->rc) + 1;
    return (leftheight > rightheight) ? leftheight : rightheight;
}

void query(const Node *root, int &size, int &height)
{
    size = getsize(root);
    height = getheight(root);
}
上一篇: Huffman coding 下一篇: Width of Binary Trees
支持 makedown语法