Specify the correct implementation of pre-order traverse algorithm for binary trees.
4 phương ánCó giải thích
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "
void preOrder(Node p) {
if (p != null) {
visit(p);
preOrder(p.left);
preOrder(p.right);
}
}". Tiền thứ tự nghĩa là thăm gốc trước rồi mới xuống nhánh trái, sau đó nhánh phải, nên lệnh thăm phải đứng trước cả hai lời gọi đệ quy; thêm vào đó điều kiện p khác null chính là chỗ dừng, nó chặn lời gọi đi vào cây rỗng. Cách viết "
void preOrder(Node p) {
if (p != null) {
preOrder(p.left);
visit(p);
preOrder(p.right);
}
}" đặt lệnh thăm giữa hai lời gọi nên cho ra thứ tự trung tố, với cây tìm kiếm thì in dãy tăng dần chứ không phải tiền thứ tự. Cách viết "
void preOrder(Node p) {
if (p == null) {
visit(p);
preOrder(p.left);
preOrder(p.right);
}
}" đảo điều kiện thành p bằng null, tức chỉ làm việc khi con trỏ rỗng, nên nó thăm một nút không tồn tại và không bao giờ đi xuống cây thật. Cách viết "
void preOrder(Node p) {
visit(p);
preOrder(p.left);
preOrder(p.right);
}" đúng trật tự thăm nhưng bỏ hẳn chỗ dừng, mỗi lá vẫn gọi tiếp vào hai con rỗng nên đệ quy lún vô hạn và chương trình đổ vì truy cập trên con trỏ rỗng.
Cùng phần 4
What is the minimum number of nodes in a nearly complete binary tree with height 4?
(In a tree the height of root is 1, and a binary tree with height h is called nearly complete if the tree is complete at level d for d = 1, 2, ..., h-1, and the leaves in the last level are all in the leftmost positions).Có lời giảiCâu hỏiTo implement an AVL tree, a concept balance factor is introduced (bal = height(right)-height(left)). Suppose an AVL tree is created by inserting to the tree the following keys sequentially:
6, 3, 7, 2, 5, 1
What is the balance factor of the node 6? (please note that the tree is still AVL)Có lời giảiCâu hỏiSuppose the binary search tree T is made by inserting the following keys consequently: 6, 7, 8, 9, 3, 2, 5, 4
What is the result of breadth-first traverse of T?Có lời giảiCâu hỏiCả 76 câu của chủ đề76 câu
Xuất hiện trong 1 bộ đề
Đi tiếp từ đây