Suppose we are considering a binary search tree. Select the most correct java code snippet that search a node with value x.
3 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: "Node search(int x)
{ Node p = root;
while(p!=null && p.info != x)
{ if(x<p.info) p = p.left;
else p=p.right;
}
return(p);
}". Phép và trong Java chỉ xét vế phải khi vế trái còn đúng, nên viết p khác null trước rồi mới đọc p.info bảo đảm không bao giờ truy cập trường của một tham chiếu rỗng; nhờ vậy khi x không có trong cây thì vòng lặp thoát với p bằng null và hàm trả về null một cách hợp lệ. Cách viết "Node search(int x)
{ Node p = root;
while(p.info != x && p!=null)
{ if(x<p.info) p = p.left;
else p=p.right;
}
return(p);
}" đảo thứ tự hai điều kiện, lần so sánh đầu đã đọc p.info nên ngay khi đi xuống hết nhánh và p thành null thì chương trình đổ vì truy cập trên tham chiếu rỗng. Cách viết "Node search(int x)
{ Node p = root;
while(p.info != x)
{ if(x<p.info) p = p.left;
else p=p.right;
}
return(p);}" bỏ hẳn việc kiểm tra null, nó chỉ chạy đúng với những khoá chắc chắn có trong cây, còn khoá không tồn tại thì vòng lặp đi quá lá rồi đọc trường của null.
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