#include "BiTree.h" #include bool BiTree::is_empty(BiTree* bt) { if (bt == nullptr) { return true; } return false; } bool BiTree::is_leaf(BiTree* bt) { if (bt->left == nullptr && bt->right == nullptr) { return true; } return false; } int BiTree::sum_leaf(BiTree* bt) { if (is_empty(bt)) { return 0; } if (is_leaf(bt)) { return bt->data; } return sum_leaf(bt->left) + sum_leaf(bt->right); } BiTree* BiTree::createNode(int data) { BiTree* newNode = new BiTree(); newNode->data = data; newNode->left = nullptr; newNode->right = nullptr; return newNode; } void BiTree::insertNode(BiTree*& bt, int value) { if (bt == nullptr) { bt = createNode(value); } else { if (value < bt->data) { insertNode(bt->left, value); } else if (value > bt->data) { insertNode(bt->right, value); } } } BiTree* BiTree::build_from_preorder_string(const std::string& preorder, size_t& index) { if (index >= preorder.size() || preorder[index] == '#') { index++; return nullptr; } BiTree* node = createNode(preorder[index++] - 'A' + 1); node->left = build_from_preorder_string(preorder, index); node->right = build_from_preorder_string(preorder, index); return node; } void BiTree::inOrder(std::ostringstream& oss) const { if (this == nullptr) return; if (left)left->inOrder(oss); oss << static_cast(data + 'A' - 1); if (right)right->inOrder(oss); } void toStringHelper(const BiTree* node, std::ostringstream& oss, const std::string& prefix, bool isLeft, bool hasSibling) { if (node != nullptr) { oss << prefix; oss << (isLeft ? (hasSibling ? "├─" : "└─") : (hasSibling ? "├─" : "└─")) << node->data << "\n"; std::string newPrefix = prefix + (isLeft ? (hasSibling ? "│ " : " ") : " "); bool hasLeftSibling = (node->left != nullptr && node->right != nullptr); toStringHelper(node->left, oss, newPrefix, true, hasLeftSibling); toStringHelper(node->right, oss, newPrefix, false, false); } } std::string BiTree::toString() { std::ostringstream oss; toStringHelper(this, oss, "", false, false); return oss.str(); } void BiTree::destory() { if (left) { left->destory(); } if (right) { right->destory(); } }