java实现二叉树前序搜索输出深度完整代码

发布时间 2023-12-17 16:22:37作者: cockroachroach
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改
class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;

public TreeNode(int val){
this.val=val;
this.left=null;
this.right=null;
}
}

public class Main {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// don't forget to initialize answer before call maximum_depth
answer=1;
maximum(root,1);
System.out.println("Maximum depth: " + answer);
}
private static int answer;
private static void maximum(TreeNode root, int depth){
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
answer = Math.max(answer, depth);
}

maximum(root.left, depth + 1);
maximum(root.right, depth + 1);}
}