Cho cây nhị phân T được biểu diễn bởi mảng một chiều A. Viết các hàm duyệt trước, duyệt giữa và duyệt sau trên cây T.
Viết các hàm duyệt trước, duyệt giữa và duyệt sau trên cây T như sau:
function preorderTraversal(A, index) {
if (index < A.length) {
console.log(A[index]); // In ra giá trị của nút hiện tại
preorderTraversal(A, 2 * index + 1); // Duyệt nút con trái
preorderTraversal(A, 2 * index + 2); // Duyệt nút con phải
}
}
function inorderTraversal(A, index) {
if (index < A.length) {
inorderTraversal(A, 2 * index + 1); // Duyệt nút con trái
console.log(A[index]); // In ra giá trị của nút hiện tại
inorderTraversal(A, 2 * index + 2); // Duyệt nút con phải
}
}
function postorderTraversal(A, index) {
if (index < A.length) {
postorderTraversal(A, 2 * index + 1); // Duyệt nút con trái
postorderTraversal(A, 2 * index + 2); // Duyệt nút con phải
console.log(A[index]); // In ra giá trị của nút hiện tại
}
}