Đây là một mã java cho việc đi lại chiều rộng đầu tiên:Chức năng du lịch đệ quy đầu tiên trong Java hoặc C++?
void breadthFirstNonRecursive(){
Queue<Node> queue = new java.util.LinkedList<Node>();
queue.offer(root);
while(!queue.isEmpty()){
Node node = queue.poll();
visit(node);
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
}
Có thể viết một hàm đệ quy để làm như vậy?
Lúc đầu, tôi nghĩ rằng điều này sẽ được dễ dàng, vì vậy tôi bước ra với điều này:
void breadthFirstRecursive(){
Queue<Node> q = new LinkedList<Node>();
breadthFirst(root, q);
}
void breadthFirst(Node node, Queue<Node> q){
if (node == null) return;
q.offer(node);
Node n = q.poll();
visit(n);
if (n.left != null)
breadthFirst(n.left, q);
if (n.right != null)
breadthFirst(n.right, q);
}
Sau đó, tôi tìm thấy nó không hoạt động. Nó thực sự giống như thế này:
void preOrder(Node node) {
if (node == null) return;
visit(node);
preOrder(node.left);
preOrder(node.right);
}
Có ai từng nghĩ về điều này trước đây không?
Ngẫu nhiên, làm BFS đệ quy có lẽ gây xếp để phát triển trong kích thước của không gian trạng thái. Nếu giải pháp của bạn ở độ sâu d, không gian ngăn xếp cần thiết để tìm giải pháp sẽ là b^d trong đó b là hệ số phân nhánh. – Eric