Tree 如何获取节点';使用DFS在树中的深度是多少?
我在打印整棵树时遇到了一个问题。当然,遍历很容易:Tree 如何获取节点';使用DFS在树中的深度是多少?,tree,depth-first-search,Tree,Depth First Search,我在打印整棵树时遇到了一个问题。当然,遍历很容易: public static void printTree(Node head){ if(head == null) return; System.out.println(head.data); printTree(head.left); printTree(head.right); } 但是,问题是我应该打印节点的深度及其数据。假设树的根是A,它的子元素分别是B和C,那么我应该打印如下内容: 0 A 1
public static void printTree(Node head){
if(head == null) return;
System.out.println(head.data);
printTree(head.left);
printTree(head.right);
}
但是,问题是我应该打印节点的深度及其数据。假设树的根是A,它的子元素分别是B和C,那么我应该打印如下内容:
0 A
1b
1 C
我该怎么做?
我是递归新手,我真的不知道如何在递归时跟踪深度
谢谢
Try adding another parameter to your function to track the depth.
public static void printTree(Node head) {
printTreeHelper(head, 0);
}
private static void printTreeHelper(Node head, int curDepth) {
if (head == null) return;
System.out.println(curDepth + head.data);
printTree(head.left, depth + 1);
printTree(head.right, depth + 1);
}
当然,您不需要使用帮助器,只需使printTree具有深度,但如果必须使用该接口,则帮助器方法将允许您继续使用它。经过一些考虑,您可以注意到发现节点时,节点的深度等于递归的深度。所以,您可以向递归函数添加指示递归深度的参数
public static void printTree(Node head, int depth){
if(head == null) return;
System.out.println(depth + " " + head.data);
printTree(head.left, depth + 1);
printTree(head.right, depth + 1);
}
当然,您可以按如下方式运行函数:printree(节点,0)代码>