题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:比较左右子树深度值,返回较大的那一个
public int TreeDepth(TreeNode root) {
if(root==null){
return 0;
}
int nLeft=TreeDepth(root.left);
int nRight=TreeDepth(root.right);
return (nLeft>nRight)?(nLeft+1):(nRight+1);
}
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
简单实现:遍历树的每个结点,调用TreeDepth得到左右子树的深度,判断即可
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
int nLeft=TreeDepth(root.left);
int nRight=TreeDepth(root.right);
int diff=nLeft-nRight;
if(diff>1||diff<-1){
return false;
}
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
7280




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



