1.题目
2.分析与解答
因为二叉树是由子二叉树构成的,所以先思考二叉树只有一层的情况
- 如果二叉树只有一个根结点,深度为1
- 有左结点无右结点,depth(左结点)+1
- 有右结点无左结点,depth(右结点)+1
- 既有左结点又有右结点, 左右结点深度进行比较
/**
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) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left > right ? left + 1 : right + 1;
}
}
时间复杂度是O(n),空间复杂度为递归栈的消耗-树的深度O(d)