题解 | #二叉树的深度#先序遍历二叉树
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
return preOrder(root, 0);
}
//先序遍历二叉树,根->左->右 每层+1,返回左节点和右节点最大的值即可
public int preOrder(TreeNode root, int depth) {
if (root == null) {
return depth;
}
depth++;
return Math.max(preOrder(root.left, depth), preOrder(root.right, depth));
}
}

