Simple Tree Traverse(遍历)

39 篇文章 0 订阅
3 篇文章 0 订阅

遍历算法

(the first node as the root node)
1.先(根)序遍历的递归算法定义:
  若二叉树非空,则依次执行如下操作:
  ⑴ 访问根结点;
  ⑵ 遍历左子树;
  ⑶ 遍历右子树。
2.中(根)序遍历的递归算法定义:
  若二叉树非空,则依次执行如下操作:
  ⑴遍历左子树;
  ⑵访问根结点;
  ⑶遍历右子树。
3.后(根)序遍历得递归算法定义:
  若二叉树非空,则依次执行如下操作:
  ⑴遍历左子树;
  ⑵遍历右子树;
  ⑶访问根结点。
#include<iostream>
using namespace std;

struct Node {
    Node *left;
    Node *right;
    int value;
    explicit Node(int t) {
        left = right = NULL;
        value = t;
    }
};

inline void insert_tree(Node *root, int v);// 建树
inline void print_inorder(Node *root); // 中序遍历
inline void print_preorder(Node *root); // 前序遍历
inline void print_postorder(Node *root); // 后序遍历
inline void recycle_tree(Node *root); // 释放内存空间

int main() {
    int n, temp;
    cin >> n;
    Node *root = NULL;
    cin >> temp;
    root = new Node(temp);
    n--;
    while (n--) {
        cin >> temp;
        insert_tree(root, temp);
    }

    cout << "Inorder:";
    print_inorder(root);
    cout << "\nPreorder:";
    print_preorder(root);
    cout << "\nPostorder:";
    print_postorder(root);
    cout << endl;
    recycle_tree(root);
}

inline void insert_tree(Node *root, int v) {
    if (v <= root->value) {
        if (root->left == NULL) root->left = new Node(v);
        else insert_tree(root->left, v);
    } else {
        if (root->right == NULL) root->right = new Node(v);
        else insert_tree(root->right, v);
    }
}

inline void print_inorder(Node *root) {
    if (root == NULL) return;
    print_inorder(root->left);
    cout << " " << root->value;
    print_inorder(root->right);
}

inline void print_preorder(Node *root) {
    if (root == NULL) return;
    cout << " " << root->value;
    print_preorder(root->left);
    print_preorder(root->right);
}

inline void print_postorder(Node *root) {
    if (root == NULL) return;
    print_postorder(root->left);
    print_postorder(root->right);
    cout << " " << root->value;
}

inline void recycle_tree(Node *root) {
    if (root == NULL) return;
    recycle_tree(root->left);
    recycle_tree(root->right);
    delete root;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值