Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

In xem phải (Right View) cây nhị phân trong C

Bài toán

In các nút nhìn thấy từ phía phải của cây nhị phân (nút cuối cùng mỗi level).

Ví dụ

Tree:
        10
      /    \
    42      93
   / \    /  \
 14  35  96  57
            /
           88

Right view: 10 93 57 88

In xem phải (Right View) cây nhị phân trong C

Thuật toán đệ quy

  • Duyệt right trước, left sau
  • Theo dõi level hiện tại và max_level đã in
  • Nếu level > max_level → in node, cập nhật max_level

Mã nguồn C

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

struct node { int data; struct node *left, *right; };

struct node* New(int item) {
    struct node* n = malloc(sizeof(struct node));
    n->data = item; n->left = n->right = NULL; return n;
}

void right_view(struct node* root, int level, int* max_level) {
    if (!root) return;
    if (*max_level < level) {
        printf("%d\t", root->data);
        *max_level = level;
    }
    right_view(root->right, level+1, max_level);
    right_view(root->left, level+1, max_level);
}

void right(struct node* root) {
    int level = 0;
    right_view(root, 1, &level);
}

int main() {
    struct node* root = New(10);
    root->left = New(42); root->right = New(93);
    root->left->left = New(14); root->left->right = New(35);
    root->right->left = New(96); root->right->right = New(57);
    root->right->left->right = New(88);
    printf("Right view: "); right(root);
    return 0;
}

Kết quả

Right view: 10 93 57 88