输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
此题用递归的思想做就非常简单了。
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null)return 0;
int leftDepth = TreeDepth(root.left);
int rightDepth = TreeDepth(root.right);
int result = 1 + ((leftDepth > rightDepth)?leftDepth:rightDepth);
return result;
}
}另外一种层次遍历的一种解法:
public int help(TreeNode root){
if(root == nu


京公网安备 11010502036488号