题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:所谓的深度是指从根结点到叶子结点的最长的路径的长度,即路径上的结点的数目。分析问题,输入根结点root,求它的深度需要先求出root左右子树的深度,取其较大值,然后加1就是当前树的深度了,即显然这是一个对二叉树后序遍历进行改编的递归过程,设计一个递归函数,输入个结点root,返回这个根结所在的树的深度。
递推关系是:
leftDepth=this.process(root.left);
rightDepth=this.process(root.right);
returnMath.max(leftDepth, rightDepth)+1;
边界条件:
If(root==null)return 0;
即对于空子树结点,显然它的深度是已知的,为0,最为边界条件或者初始条件。
这是一个基本的递归函数构造过程,很简单,只有一个返回值。
//求深度,先求左右子树的深度,再求当前树的深度。对后序遍历的递归过程进行改造即可
public class Solution {
public int TreeDepth(TreeNode root) {
//特殊输入
if(root==null) return 0;
//调用递归函数解决问题
return this.process(root);
}
//设计一个递归函数用来求出一棵二叉树的深度
private int process(TreeNode root){
//递归函数的边界条件
if(root==null) return 0;
//①求左子树的深度
int leftDepth=this.process(root.left);
//②求右子树的深度
int rightDepth=this.process(root.right);
//③处理当前结点,求当前树的深度
int depth=Math.max(leftDepth,rightDepth)+1;
//返回结果
return depth;
}
}