Bài toán
In các nút nhìn thấy từ phía trái của cây nhị phân (nút đầu tiên mỗi level).
Ví dụ
Tree:
1
/ \
0 3
/ \
2 4
Left view: 1 0 2

Thuật toán
- Đệ quy: left trước, right sau
- Theo dõi highest_level đã in
- Nếu level > highest_level → in, cập nhật
Mã nguồn C
#include <stdio.h>
#include <stdlib.h>
struct node { int data; struct node *left, *right; };
struct node* New(int data) {
struct node* n = malloc(sizeof(struct node));
n->data = data; n->left = n->right = NULL; return n;
}
void left_view(struct node* root, int level, int* highest) {
if (!root) return;
if (*highest < level) {
printf("%d\t", root->data);
*highest = level;
}
left_view(root->left, level+1, highest);
left_view(root->right, level+1, highest);
}
void left(struct node* root) {
int h=0; left_view(root, 1, &h);
}
int main() {
struct node* root = New(1);
root->left = New(0); root->right = New(3);
root->right->left = New(2); root->right->right = New(4);
printf("Left view: "); left(root);
return 0;
}
Kết quả
Left view: 1 0 2