Binärer Baum
-
Hallo,
ich habe eine Frage. Ich gerade beim binären Baum. und habe bisher folgendes.
Node.h#ifndef Node_h #define Node_h Node_h class CNode { private: CNode** pChildren; char value; int key; public: CNode(int key, char value); ~CNode(void); //set void SetChild(int index, CNode* pChild); void SetKey(int key); void SetValue(char value); bool add(int key, char value); //get int GetKey(); CNode* GetChild(int index); }; #endifNode.cpp
#include "StdAfx.h" #include ".\node.h" #include <stdlib.h> CNode::CNode(int key, char value) { pChildren = new CNode*[2]; for(int i = 0; i < 2; i++) { pChildren[i] = NULL; } this->value = value; this->key = key; } CNode::~CNode(void) { } //set void CNode::SetChild(int index, CNode* pChild) { this->pChildren[index] = pChild; } void CNode::SetKey(int key) { this->key = key; } void CNode::SetValue(char value) { this->value = value; } bool CNode::add(int key, char value) { bool result = true; if (key < this->key) { if (this->pChildren[0] != NULL) { result = this->pChildren[0]->add(key, value); } else { // In diesem Fall muss ein neuer Knoten mit dem neuen Schlüssel erzeugt werden. this->pChildren[0] = new CNode(key, value); } } else if (key > this->key) { if (this->pChildren[1] != NULL) { result = this->pChildren[1]->add(key, value); } else { // In diesem Fall muss ein neuer Knoten mit dem neuen Schlüssel erzeugt werden. this->pChildren[1] = new CNode(key, value); } } else if (key == this->key) { // Der Schlüssel existiert schon und darf nicht überschrieben werden. result = false; } return result; } //get CNode* CNode::GetChild(int index) { return this->pChildren[index]; } int CNode::GetKey() { return this->key; }Tree.h
#ifndef Tree_h #define Tree_h Tree_h #include "Node.h" class CTree { private: CNode* pRoot; public: CTree(void); ~CTree(void); bool Add(int key, char value); }; #endifTree.cpp
#include "StdAfx.h" #include ".\tree.h" #include <stdlib.h> CTree::CTree(void) { pRoot = NULL; } CTree::~CTree(void) { } bool CTree::Add(int key, char value) { if(pRoot == NULL) { this->pRoot = new CNode(key, value); return true; } else { return this->pRoot->add(key, value); } }Eine Frage zur add Methode in Node.cpp.
Diese Methode habe ich so teilweise von jemanden bekommen und in Tree.h die bool Add. Den Rest hab ich selber getippt.
Ich verstehe nicht genau was die add methode in Node.cpp macht.
Sie ist rekursiv, aber wo ist der Rekursionsankser und wo wird
die bool Variable result ausgewrtet ?
Ich hab nene Kopf wie eine Wassermelone.Kan mir bitte jemand den Code aus der add Methode von Node.cpp erklären ?
Danke,
cmos
-
Dieser Thread wurde von Moderator/in SideWinder aus dem Forum DOS und Win32-Konsole in das Forum C++ verschoben.
Im Zweifelsfall bitte auch folgende Hinweise beachten:
C/C++ Forum :: FAQ - Sonstiges :: Wohin mit meiner Frage?Dieses Posting wurde automatisch erzeugt.