-
二叉树结构定义
template <typename DataType> struct BTNode { DataType value; struct BTNode *lchild; struct BTNode *rchild; explicit BTNode(DataType x) : value(x), lchild(NULL), rchild(NULL) {} };
数据类型用template模板定义,创建一个树节点可以写为:
BTNode<DataType> *p = new BTNode(x);
-
广义表建立二叉树
// Translate the string to a BTree // sample:A(B(,G),C(D(F),E)) // output: // A // / \ // B C // \ / \ // G D E // / // F BTNode<char>* StrToBTree(const char *str, BTNode<char> *&T) { if (!str) return NULL; std::stack <BTNode<char>*> st; int flag = -1; BTNode<char> *p = NULL; if (T) { free(T); T = NULL; } for (int i = 0; str[i] != '\0'; i++) { switch(str[i]) { case '(': if (p) { flag = 0;// start_left_child st.push(p); p = NULL; } break; case ')': st.pop(); break; case ',': flag = 1; // start_right_child break; default: p = new BTNode<char>(str[i]); if (!T) T = p; // save the original root else { switch (flag) { case 0: st.top()->lchild = (BTNode*)p; break; case 1: st.top()->rchild = (BTNode*)p; break; default: break; } } break; } } return T; }
-
二叉树输出广义表
// Translate the BTree to a string // sample: // A // / \ // B C // \ / \ // G D E // / // F // output:A(B(,G),C(D(F),E)) char* BTreeToStr(BTNode<char> *T, char *str) { if (!str) return NULL; if (!T) return NULL; static int i = 0; str[i++] = T->value; if (T->lchild || T->rchild) str[i++] = '('; BTreeToStr((BTNode<char>*)T->lchild, str); if (T->rchild) str[i++] = ','; BTreeToStr((BTNode<char>*)T->rchild, str); if (T->lchild || T->rchild) str[i++] = ')'; str[i] = 0; return str; }
广义表方式创建二叉树及二叉树输出广义表(C++)
最新推荐文章于 2024-08-07 17:22:53 发布