c_cpp CPP:树实施

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp CPP:树实施相关的知识,希望对你有一定的参考价值。

/*
  Each "generation" of the nodes of the tree is a new level, starting at level 1 in the root.
  
  Leaf Node - node that has no children
  Leafless - node with one or more children attached
  Siblings - nodes that share the same parent node
*/

#include<cassert>
#include<iostream>

class Node
{
public:
	Node(int data)
		: _data(data)
		, _child(nullptr)
		, _next(nullptr)
		, _prev(nullptr)
	{
	}

	~Node()
	{
		if (_child != nullptr)
			delete _child;

		if (_next != nullptr)
			delete _next;
	}

	void AddChild(Node* node)
	{
		assert(node != nullptr);
		if (_child == nullptr)
		{
			_child = node;
		}
		else
		{
			_child->AddChild(node);
		}
	}

	void AddSibling(Node* node)
	{
		assert(node != nullptr);
		if (_next == nullptr)
		{
			_next = node;
			node->_prev = this;
		}
		else
		{
			_next->AddSibling(node);
		}
	}

	void Display()
	{
		std::cout << _data << std::endl;
		if (_next != nullptr)
		{
			_next->Display();
		}

		if (_child != nullptr)
		{
			_child->Display();
		}
	}

	Node* Search(int value)
	{
		if (_data == value)
			return this;

		if (_next != nullptr)
		{
			Node* node = _next->Search(value);
			if (node != nullptr)
			{
				return node;
			}
		}

		if (_child != nullptr)
		{
			Node* node = _child->Search(value);
			if (node != nullptr)
			{
				return node;
			}
		}

		return nullptr;
	}


private:
	int   _data;

	Node* _child;
	Node* _next;
	Node* _prev;
};

int main()
{
	Node* root = new Node(1);

	root->AddChild(new Node(2));

	Node* sub_tree = new Node(3);
	sub_tree->AddChild(new Node(5));
	sub_tree->AddChild(new Node(6));

	root->AddChild(sub_tree);
	root->AddChild(new Node(4));

	root->Display();

	Node* node = root->Search(5);
	assert(node != nullptr);

	node = root->Search(9);
	assert(node == nullptr);

	delete root;

	return 0;
}

以上是关于c_cpp CPP:树实施的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 实施一个特里

c_cpp 实施sqrt

c_cpp 实施红黑树

c_cpp BST实施和遍历

c_cpp 双重链表实施

c_cpp 双重链表OO实施