import java.util.Scanner;标签:right,TreeNode,前序,二叉树,answer,java,root,public,left From: https://www.cnblogs.com/cockroachroach/p/17909225.html
// 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);}
}