原题链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/
1. 题目介绍
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
给定一个二叉树,找到树的最大深度。最大深度是指从头节点到最远的叶子节点的距离。
Note: A leaf is a node with no children.
叶子节点就是指没有子节点的节点
Example:
Given binary tree [3,9,20,null,null,15,7]
return its depth = 3.
2. 解题思路
使用深度优先搜索的方法寻找每一个叶子节点。
利用递归函数,每层递归都返回左右子树中高度最高的那个树的高度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return helper(0,root);
}
public int helper(int depth,TreeNode root){
if(root == null){
return depth;
}
if(root.left == null && root.right == null){
return depth+1;
}
return Math.max(helper(depth+1,root.left) , helper(depth+1,root.right) );
}
}