C++ 普通二叉树元素的来源问题

插入和删除无意义,初始时的二叉树的元素如何得来呢?就这里卡住了,我想写程序也无法测试,因为我根本就没有元素,插入又不知道

阅读 1.5k
1 个回答

比如,如果你要生成以下一个树:

                     a
                   /   \
                  b      c
                 / \    / \
                d   e  f   g   

可以用以下程序初始化,测试前序,中序,后序输出:

#include <iostream>

struct Node {
    char val;
    struct Node* left;
    struct Node* right;
    Node(int v) : val(v), left(NULL), right(NULL) {}
};
 
struct Node* init() {
    struct Node* root;

    root               = new struct Node('a');
    root->left         = new struct Node('b');
    root->right        = new struct Node('c');
    root->left->left   = new struct Node('d');
    root->left->right  = new struct Node('e');
    root->right->left  = new struct Node('f');
    root->right->right = new struct Node('g');
       
    return root;
}

// 测试前序输出 
void preorder_output(const struct Node* root) {
    if (root == NULL)
        return ;
    std::cout << root->val << "\t";
    preorder_output(root->left);
    preorder_output(root->right);
}

// 测试中序输出 
void inorder_output(const struct Node* root) {
    if (root == NULL)
        return ;
    inorder_output(root->left);
    std::cout << root->val << "\t";
    inorder_output(root->right);
}

// 测试后序输出 
void postorder_output(const struct Node* root) {
    if (root == NULL)
        return ;
    postorder_output(root->left);
    postorder_output(root->right);
    std::cout << root->val << "\t";
}

int main() {
    struct Node* root = init();
    
    std::cout << std::endl << "前序输出:";
    preorder_output(root);
    
    std::cout << std::endl << "中序输出:"; 
    inorder_output(root);
    
    std::cout << std::endl << "后序输出:";
    postorder_output(root);
    
    return 0;
} 

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题