题目:
二叉树的深度-LeetCode 原文链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
思路:
- 就使用递归深度优先遍历就好了,如果当前结点非空,那么返回深度就默认+1
- 时间复杂度为O(n),因为每个结点只被访问一次
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}else{
return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
}
}
}