求输入根节点的深度(最长路径)
递归思路,如果把树分成三部分,求树的左树深度,求右树深度,则深度就为更大的一个加1.使用后序遍历,得到左和右的深度之后就可以了。
public class Solution {
public int TreeDepth(TreeNode root){
if(root==null){
return 0;
}
int ld=TreeDepth(root.left);
int rd=TreeDepth(root.right);
if(ld>rd) return ld+1;
else return rd+1;
}
}
求最小深度
与最大深度的不同主要是
当 root 节点左右孩子都为空时,返回 1
当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度
当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值
class Solution {
public int minDepth(TreeNode root) {
if(root==null)return 0;
if(root.left==null && root.right==null)return 1;
if(root.left==null)return 1+minDepth(root.right);
if(root.right==null)return 1+minDepth(root.left);
int min=Math.min(minDepth(root.left),minDepth(root.right));
return min+1;
}
}
判断一个树是不是平衡二叉树
平衡二叉树也就是左子树和右子树的深度相差不超过1,利用上面求深度的方法可以很简单的求出左右子树的深度。然后即可求出这个节点是否是平衡的,然后再递归判断它的左右节点是否是平衡的,判断每个节点即可完成。(自上而下)
但这样经过了太多的遍历,所以稍微改一下,在第一遍上来的时候就在过程中顺便判断这个节点是不是平衡的,如果不平衡后面的就不用遍历了,完成剪枝,大大减少了遍历的次数。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
return core(root)==-1?false:true;
}
public int core(TreeNode root){
if(root==null){
return 0;
}
int left=core(root.left);
if(left==-1) return -1;
int right=core(root.right);
if(right==-1) return -1;
if(Math.abs(left-right)>1)return -1;
return 1+Math.max(left,right);
}
}