算法要求:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
/**
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) {
}
}
思路:
1.若根节点是空节点,则为空树,深度为0;
2.若根节点不为空,则选择左子树和右子树中深度大的为新树,原树的深度是新树的深度+1;
3.递归
解题过程:
/**
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 cLeft = TreeDepth(root.left); //计算左子树深度
int cRight = TreeDepth(root.right); //计算右子树深度
return Math.max(cLeft,cRight)+1;
}
}
本文介绍了一种计算二叉树深度的方法。通过递归地计算左右子树的最大深度,并取其较大值加一来得到整棵树的深度。适用于计算机科学领域的数据结构与算法学习。
570

被折叠的 条评论
为什么被折叠?



