From 4f9bd7ae24acef1824134df9a62521185e3d1aa3 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Tue, 15 Jan 2019 22:25:39 -0600 Subject: Tree height done in C++!!! Wow, this is so frustrating at times but in the end so much fun!!! My real issue was creating and using a member function called getChildren, which returns a node's children. It turned out if I accessed the children member variable directly (since it's public), problem solved! Another somewhat interesting observation is that using "vector" in the main getHeight function seems slightly more efficient (memory wise) than "vector". I also used Visual Studio Community C++ 2017, which was cool as well!--- Sources/DataStructure.cpp | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) (limited to 'Sources') diff --git a/Sources/DataStructure.cpp b/Sources/DataStructure.cpp index b82f908..91fdf86 100644 --- a/Sources/DataStructure.cpp +++ b/Sources/DataStructure.cpp @@ -23,24 +23,16 @@ public: parent = theParent; parent->children.push_back(this); } - - vector getChildren() { - return children; - } - - void setKey(int theKey) { - key = theKey; - } }; int treeLevelCounter(vector &nodes, int rootIndex) { int levelCounter = 1; queue q; int popCount = 0; - int childrenCount = nodes[rootIndex].getChildren().size(); + int childrenCount = nodes[rootIndex].children.size(); int grandChildrenCount = 0; for (int i = 0; i < childrenCount; i++) { - q.push(nodes[rootIndex].getChildren()[i]); + q.push(nodes[rootIndex].children[i]); } while (!q.empty()) { if (popCount < childrenCount) { @@ -67,9 +59,8 @@ int getHeight(vector &a) { vector nodes; nodes.resize(a.size()); int rootIndex = 0; - for (int i = 0; i < a.size(); i++) { + for (size_t i = 0; i < a.size(); i++) { int parentIndex = a[i]; - nodes[i].setKey(i); if (parentIndex == -1) { rootIndex = i; } else { -- cgit v1.2.3