Giới thiệu
Cho cây nhị phân và số nguyên N. Tìm nút thứ N trong thứ tự duyệt inorder (trái - gốc - phải).
Ví dụ minh họa
Đầu vào
N = 6

Đầu ra
3
Giải thích
Inorder: 4, 2, 5, 1, 6, 3, 7 → phần tử thứ 6 là 3
Phương pháp giải: Đệ quy inorder với bộ đếm
Duyệt inorder đệ quy, tăng bộ đếm static. Khi bộ đếm = N, in giá trị nút.
Chương trình minh họa
#include <iostream>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* createNode(int item) {
Node* temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
void findInOrderTraversalRec(Node* node, int N) {
static int count = 0;
if (!node) return;
if (count <= N) {
findInOrderTraversalRec(node->left, N);
count++;
if (count == N)
cout << node->data;
findInOrderTraversalRec(node->right, N);
}
}
int main() {
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
int N = 6;
cout << N << "th node in inorder traversal is ";
findInOrderTraversalRec(root, N);
return 0;
}
Đầu ra
6th node in inorder traversal is 3