求二叉树高度(更新:用C++14编写)

因为树是递归定义的,所以用递归算法很方便。

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
using namespace std;

struct Node {
	char data;
	Node *lchild;
	Node *rchild;
};

void High(Node *T, int &h)
{
	if (T == NULL)
		h = 0;
	else {
		int left_h;
		High(T->lchild, left_h);
		int right_h;
		High(T->rchild, right_h);

		h = 1 + max(left_h, right_h);
	}
}

Node *CreateBiTree(Node *&T) {  // 算法6.4
	// 按先序次序输入二叉树中结点的值(一个字符),空格字符表示空树,
	// 构造二叉链表表示的二叉树T。
	char ch;
	cin >> ch;
	if (ch == '#')
		T = NULL;
	else {
		if (!(T = (Node *)malloc(sizeof(Node))))
			return 0;
		T->data = ch;              // 生成根结点
		CreateBiTree(T->lchild);   // 构造左子树
		CreateBiTree(T->rchild);   // 构造右子树
	}
	return T;
} // CreateBiTree

void Free(Node *&T)
{
	if (T == NULL)
		return;

	Free(T->lchild);
	//	T->lchild = NULL;
	Free(T->rchild);
	//	T->rchild = NULL;
	free(T);
	T = NULL;
}

int main(int argc, char **argv)
{
	freopen("cin.txt", "r", stdin);

	Node *T = NULL;
	CreateBiTree(T);

	int height;
	High(T, height);
	cout << height << endl;

	Free(T);

	return 0;
}

/* cin.txt:
A
B
C
#
#
D
E
#
G
#
#
F
#
#
#
*/


构造的树:

输出为5。


2015.06.03更新

下面用 C++14 标准重写了程序,定义了 Node 和 Tree 两个类。

#ifndef TREE_H
#define TREE_H

#include 

template 
class Node {
	private:
		DataType data_;
		std::shared_ptr left_;
		std::shared_ptr right_;

	public:
		Node(const DataType &data = DataType(),
				const std::shared_ptr &left = nullptr,
				const std::shared_ptr &right = nullptr)
			: data_(data), left_(left), right_(right) {}

		auto data() const {
			return data_;
		}

		/*
		 * deep copy
		 */
		std::shared_ptr copy() const {
			auto left = (left_ == nullptr ? nullptr : left_->copy());
			auto right = (right_ == nullptr ? nullptr : right_->copy());

			return std::make_shared(data_, left, right);
		}
};

template 
class Tree {
	private:
		std::shared_ptr> root_;

	public:
		Tree(const std::shared_ptr> &root = nullptr) : root_(root) {}

		/*
		 * deep copy
		 */
		Tree(const Tree &that) : root_(that.root_->copy()) {}

		/*
		 * deep assignment
		 */
		Tree & operator=(const Tree &that) {
			if (this != &that) {
				root_ = that.root_->copy();
			}

			return *this;
		}

		auto root() const {
			return root_;
		}
};

#endif

下面是测试程序。

#include 
#include "tree.h"

int main() {
	auto pnode = std::make_shared>(2, nullptr, nullptr);
	auto pnode2 = pnode->copy();
	std::cout << pnode->data() << std::endl;
	std::cout << pnode2->data() << std::endl;

	Tree t(pnode);
	auto t2 = t;
	std::cout << t2.root()->data() << std::endl;
	std::cout << t.root()->data() << std::endl;

	return 0;
}


你可能感兴趣的:(Data,Structure,C/C++)