二叉树的基本操作

实验内容

1.输入字符序列,建立二叉链表。

     2.中序遍历二叉树:递归算法。

     3.中序遍历二叉树:非递归算法。(最好也能实现先序,后序非递归算法)

     4.求二叉树的高度 。

     5.求二叉树的叶子个数。

     7.借助队列实现二叉树的层次遍历。  

     8.在主函数中设计一个简单的菜单,分别调试上述算法。

代码实现

        python实现

import queue

# 定义二叉树节点类
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

# 1. 从字符序列构建二叉树
def build_tree(data):
    if not data:
        return None
    nodes = [TreeNode(char) if char != '#' else None for char in data]
    kids = nodes[::-1]
    root = kids.pop()
    for node in nodes:
        if node:
            if kids: node.left = kids.pop()
            if kids: node.right = kids.pop()
    return root

# 2. 中序遍历二叉树(递归)
def inorder_recursive(node):
    return inorder_recursive(node.left) + [node.value] + inorder_recursive(node.right) if node else []

# 3. 中序遍历二叉树(非递归)
def inorder_iterative(root):
    result, stack = [], []
    while stack or root:
        if root:
            stack.append(root)
            root = root.left
        else:
            root = stack.pop()
            result.append(root.value)
            root = root.right
    return result

# 先序遍历非递归
def preorder_iterative(root):
    if not root:
        return []
    result, stack = [], [root]
    while stack:
        node = stack.pop()
        if node:
            result.append(node.value)
            stack.append(node.right)
            stack.append(node.left)
    return result

# 后序遍历非递归
def postorder_iterative(root):
    if not root:
        return []
    result, stack = [], [root]
    while stack:
        node = stack.pop()
        if node:
            result.append(node.value)
            stack.append(node.left)
            stack.append(node.right)
    return result[::-1]

# 4. 计算二叉树的高度
def tree_height(node):
    if not node:
        return 0
    return 1 + max(tree_height(node.left), tree_height(node.right))

# 5. 计算二叉树的叶子节点个数
def count_leaves(node):
    if not node:
        return 0
    if not node.left and not node.right:
        return 1
    return count_leaves(node.left) + count_leaves(node.right)

# 8. 层次遍历二叉树
def level_order_traversal(root):
    if not root:
        return []
    result, q = [], queue.Queue()
    q.put(root)
    while not q.empty():
        node = q.get()
        result.append(node.value)
        if node.left:
            q.put(node.left)
        if node.right:
            q.put(node.right)
    return result

# 9. 主函数菜单
def main():
    tree = None
    while True:
        print("\nMENU:")
        print("1. 输入字符序列,建立二叉链表")
        print("2. 中序遍历二叉树(递归)")
        print("3. 中序遍历二叉树(非递归)")
        print("4. 先序遍历二叉树(非递归)")
        print("5. 后序遍历二叉树(非递归)")
        print("6. 求二叉树的高度")
        print("7. 求二叉树的叶子个数")
        print("8. 层次遍历二叉树")
        print("9. 退出")
        choice = input("请输入你的选择: ")

        if choice == '1':
            seq = input("请输入字符序列(用'#'表示空节点): ")
            tree = build_tree(seq)
            print("二叉树已建立。")
        elif choice == '2':
            if tree:
                print("中序遍历(递归): ", inorder_recursive(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '3':
            if tree:
                print("中序遍历(非递归): ", inorder_iterative(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '4':
            if tree:
                print("先序遍历(非递归): ", preorder_iterative(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '5':
            if tree:
                print("后序遍历(非递归): ", postorder_iterative(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '6':
            if tree:
                print("二叉树的高度: ", tree_height(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '7':
            if tree:
                print("二叉树的叶子个数: ", count_leaves(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '8':
            if tree:
                print("层次遍历: ", level_order_traversal(tree))
            else:
                print("请先建立二叉树。")
        elif choice == '9':
            break
        else:
            print("无效选择,请重试。")

if __name__ == "__main__":
    main()

结果展示

括号法创建

C语言实现

//括号法创建二叉树

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct TreeNode {
    char val;
    struct TreeNode* left;
    struct TreeNode* right;
} TreeNode;

typedef struct StackNode {
    TreeNode* treeNode;
    struct StackNode* next;
} StackNode;

typedef struct QueueNode {
    TreeNode* treeNode;
    struct QueueNode* next;
} QueueNode;

typedef struct Queue {
    QueueNode* front;
    QueueNode* rear;
} Queue;

TreeNode* createNode(char val) {
    if (val == '#') return NULL;
    TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
    node->val = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

void skipSpaces(const char** str) {
    while (**str == ' ') {
        (*str)++;
    }
}

TreeNode* parseTree(const char** str) {
    skipSpaces(str);

    if (**str == '\0' || **str == '#') {
        if (**str == '#') (*str)++;
        return NULL;
    }

    TreeNode* root = createNode(**str);
    (*str)++;

    skipSpaces(str);

    if (**str == '(') {
        (*str)++;
        root->left = parseTree(str);
        skipSpaces(str);
        if (**str == ',') {
            (*str)++;
            root->right = parseTree(str);
        }
        skipSpaces(str);
        if (**str == ')') {
            (*str)++;
        }
    }

    return root;
}

void printTree(TreeNode* root) {
    if (!root) return;
    printf("%c", root->val);
    if (root->left || root->right) {
        printf("(");
        printTree(root->left);
        printf(",");
        printTree(root->right);
        printf(")");
    }
}

void freeTree(TreeNode* root) {
    if (!root) return;
    freeTree(root->left);
    freeTree(root->right);
    free(root);
}

// 递归前序遍历
void preorderRecursive(TreeNode* root) {
    if (!root) return;
    printf("%c ", root->val);
    preorderRecursive(root->left);
    preorderRecursive(root->right);
}

// 递归中序遍历
void inorderRecursive(TreeNode* root) {
    if (!root) return;
    inorderRecursive(root->left);
    printf("%c ", root->val);
    inorderRecursive(root->right);
}

// 递归后序遍历
void postorderRecursive(TreeNode* root) {
    if (!root) return;
    postorderRecursive(root->left);
    postorderRecursive(root->right);
    printf("%c ", root->val);
}

// 辅助函数:压栈
void push(StackNode** stack, TreeNode* treeNode) {
    StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
    newNode->treeNode = treeNode;
    newNode->next = *stack;
    *stack = newNode;
}

// 辅助函数:出栈
TreeNode* pop(StackNode** stack) {
    if (!*stack) return NULL;
    StackNode* top = *stack;
    TreeNode* treeNode = top->treeNode;
    *stack = top->next;
    free(top);
    return treeNode;
}

// 非递归前序遍历
void preorderIterative(TreeNode* root) {
    if (!root) return;
    StackNode* stack = NULL;
    push(&stack, root);
    while (stack) {
        TreeNode* node = pop(&stack);
        printf("%c ", node->val);
        if (node->right) push(&stack, node->right);
        if (node->left) push(&stack, node->left);
    }
}

// 非递归中序遍历
void inorderIterative(TreeNode* root) {
    StackNode* stack = NULL;
    TreeNode* current = root;
    while (current || stack) {
        while (current) {
            push(&stack, current);
            current = current->left;
        }
        current = pop(&stack);
        printf("%c ", current->val);
        current = current->right;
    }
}

// 非递归后序遍历
void postorderIterative(TreeNode* root) {
    if (!root) return;
    StackNode* stack = NULL, * output = NULL;
    push(&stack, root);
    while (stack) {
        TreeNode* node = pop(&stack);
        push(&output, node);
        if (node->left) push(&stack, node->left);
        if (node->right) push(&stack, node->right);
    }
    while (output) {
        printf("%c ", pop(&output)->val);
    }
}

// 辅助函数:入队
void enqueue(Queue* queue, TreeNode* treeNode) {
    QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
    newNode->treeNode = treeNode;
    newNode->next = NULL;
    if (!queue->rear) {
        queue->front = queue->rear = newNode;
    }
    else {
        queue->rear->next = newNode;
        queue->rear = newNode;
    }
}

// 辅助函数:出队
TreeNode* dequeue(Queue* queue) {
    if (!queue->front) return NULL;
    QueueNode* front = queue->front;
    TreeNode* treeNode = front->treeNode;
    queue->front = front->next;
    if (!queue->front) {
        queue->rear = NULL;
    }
    free(front);
    return treeNode;
}

// 层次遍历(广度优先遍历)
void levelOrder(TreeNode* root) {
    if (!root) return;
    Queue queue = { 0 };
    enqueue(&queue, root);
    while (queue.front) {
        TreeNode* node = dequeue(&queue);
        printf("%c ", node->val);
        if (node->left) enqueue(&queue, node->left);
        if (node->right) enqueue(&queue, node->right);
    }
}

// 计算叶子节点数量
int countLeaves(TreeNode* root) {
    if (!root) return 0;
    if (!root->left && !root->right) return 1;
    return countLeaves(root->left) + countLeaves(root->right);
}

// 计算树的高度
int treeHeight(TreeNode* root) {
    if (!root) return 0;
    int leftHeight = treeHeight(root->left);
    int rightHeight = treeHeight(root->right);
    return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}

void test() {
    printf("**********括号法创建二叉树************\n");
    printf("\n请输入字符序列:\n");
    const char* input;
    input = (char*)malloc(100 * sizeof(char));
    scanf("%s", input);
    const char* str = input;
    TreeNode* root = parseTree(&str);

    printf("已成功创建树:");
    printTree(root);
    printf("\n");

    printf("递归前序遍历: ");
    preorderRecursive(root);
    printf("\n");

    printf("递归中序遍历: ");
    inorderRecursive(root);
    printf("\n");

    printf("递归后序遍历: ");
    postorderRecursive(root);
    printf("\n");

    printf("非递归前序遍历: ");
    preorderIterative(root);
    printf("\n");

    printf("非递归中序遍历: ");
    inorderIterative(root);
    printf("\n");

    printf("非递归后序遍历: ");
    postorderIterative(root);
    printf("\n");

    printf("层次遍历: ");
    levelOrder(root);
    printf("\n");

    printf("叶子节点数量: %d\n", countLeaves(root));
    printf("树的高度: %d\n", treeHeight(root));

    freeTree(root);
    return 0;
}


int main() {
    test();
    return 0;
}

//     A(B(C,#),E(F(#,G),H))

结果展示

  • 19
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值