Suppose we are considering a binary search tree. Select the most correct java code snippet that search a node with value x on the sub-tree with root p.
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(Node p, int x)
{ if(p==null) return(null);
if(p.info==x) return(p);
if(x<p.info)
return(search(p.left,x));
else
return(search(p.right,x));
}". Phép tìm đệ quy trên cây nhị phân tìm kiếm cần hai chỗ dừng: tham chiếu rỗng thì trả về null vì đã đi quá lá, và nút đang xét mang đúng x thì trả về chính nó; còn lại dùng thứ tự của cây, x nhỏ hơn giá trị nút thì chỉ có thể nằm bên nhánh trái, ngược lại nằm bên nhánh phải. Cách viết "Node search(Node p, int x)
{if(p.info==x) return(p);
if(x<p.info)
return(search(p.left,x));
else
return(search(p.right,x));
}" thiếu chỗ dừng cho tham chiếu rỗng, nó đọc p.info ngay nên khi x không có trong cây, lời gọi xuống tới con rỗng của một lá sẽ truy cập trường của null và chương trình đổ. Cách viết "Node search(Node p, int x)
{ if(p==null) return(null);
if(p.info==x) return(p);
if(x<p.info)
return(search(p.right,x));
else
return(search(p.left,x));}" có đủ hai chỗ dừng nhưng rẽ ngược: x nhỏ hơn giá trị nút lại đi sang nhánh phải, nơi chỉ chứa khoá lớn hơn, nên phép tìm bỏ qua đúng nửa cây có thể chứa x và trả về null dù x nằm trong cây.
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