关于#数据结构#的问题:创建一个具有十个节点的完全二叉树(注意是完全二叉树)要求:先定义二叉树的节点,该程序返回创建的二叉树的根节点地址

请问如何创建一个具有十个节点的完全二叉树
(注意是完全二叉树)

完全二叉树如图所示

img

package answers;

public class TreeNode {
    public int val;//结点的值
    public TreeNode left;//结点的左孩子
    public TreeNode right;//结点的右孩子

    public TreeNode(int val) {
        this.val = val;     // 这个结点中的值是 val
        this.left = null;   // 这个结点的左孩子是 null:不存在 —— 左子树是空树
        this.right = null;  // 这个结点的有孩子是 null;不存在 —— 右子树是空树
    }
}

package answers;

public class TreeOperations {
    public static TreeNode 手动构建二叉树() {
        TreeNode a = new TreeNode('A');
        TreeNode b = new TreeNode('B');
        TreeNode c = new TreeNode('C');
        TreeNode d = new TreeNode('D');
        TreeNode e = new TreeNode('E');
        TreeNode f = new TreeNode('F');
        TreeNode g = new TreeNode('G');
        TreeNode h = new TreeNode('H');
        TreeNode i = new TreeNode('I');
        TreeNode j = new TreeNode('J');

        // 手动构建其关系
        a.left = b; a.right = c;
        b.left = d; b.right = e;
        c.left = f; c.right = g;
        d.left = h; d.right = i;  
        e.left = j; e.right = null;
        f.left = null; f.right = null;//都为空可以省略
        g.left = null; g.right = null;
        h.left = null; h.right = null;
        i.left = null; i.right = null;
        j.left = null; j.right = null; 

        // 返回根结点即可
        return a;
    }
    public static void main(String[] args) {
        //主函数根据需求填写
    }
}

answers是自己定义的包名,就是这样的了,望采纳!

img

GPT


#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int data) {
    struct Node* node = (struct Node*) malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

void buildCompleteTree(struct Node* root, int i, int n) {
    if (i > n)
        return;
    root = newNode(i);
    if (2 * i <= n)
        root->left = newNode(2 * i);
    if (2 * i + 1 <= n)
        root->right = newNode(2 * i + 1);
    buildCompleteTree(root->left, 2 * i, n);
    buildCompleteTree(root->right, 2 * i + 1, n);
}

void inorderTraversal(struct Node* root) {
    if (root == NULL)
        return;
    inorderTraversal(root->left);
    printf("%d ", root->data);
    inorderTraversal(root->right);
}

int main() {
    struct Node* root = NULL;
    buildCompleteTree(root, 1, 10);
    inorderTraversal(root);
    return 0;
}

在这个程序中,我们使用了 struct Node 定义了一个二叉树节点的结构体。newNode 函数用于创建一个新的节点。buildCompleteTree 函数用于构建一个完全二叉树,它接受三个参数:根节点、当前节点的索引值以及节点的总数。inorderTraversal 函数用于中序遍历二叉树。

在 main 函数中,我们首先初始化根节点,然后调用 buildCompleteTree 函数构建完全二叉树。最后,我们调用 inorderTraversal 函数对二叉树进行中序遍历,并打印每个节点的值。