题目描述:
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]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
思路:
递归:
需要定义一个全局变量来记录遍历当前节点处二叉树的最大深度。每次深度搜索时,当前深度都要进行+1操作,并且每到达一个新的节点处,都需要将当前深度和全局的最大深度进行比较,若当前深度大于全局最大深度,则更新全局最大深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int depth=0;
public int maxDepth(TreeNode root) {
helper(root,1);
return depth;
}
private void helper(TreeNode node,int currDepth){
if(node==null){
return;
}
if(currDepth>depth){
depth=currDepth;
}
helper(node.left,currDepth+1);
helper(node.right,currDepth+1);
}
}
分治:
关于二叉树的问题,都推荐用分治的思想去解决,清楚明了。本题用分治的方法就是,定义一种递归的算法,从根节点开始,我们就递归的去寻找当前根节点对应的左子树和右子树的深度,那么整棵树的最大深度就是左子树,右子树最大深度中的较大值机上当前节点的深度(1)。
//root->depth
public int maxDepth(TreeNode root) {
//递归的出口
if(root==null){
return 0;
}
//否则,不管三七二十一,去求得左子树和右子树的结果
int left=maxDepth(root.left);
int right=maxDepth(root.right);
//最后,考虑left,right和整棵树的最大值之间的关系
return Math.max(left,right)+1;
}