判断平衡二叉树
题目:
分析:二叉树的题目一般选择递归求解,通过判断原式的返回值和入口参数,发现这里原式就可以拿来递归。这题的关键是找到当前树和子树的关于平衡二叉树判断的联系。把求当前树平衡转移到对子树的平衡判断中。比如先是判断以根节点为代表的树是否为配合二叉树,递推关系是:它的左子树和右子树都分别需要是平衡二叉树,然后左子树的深度和右子树的深度相差小于2。这样就把判断转移到了子树,最后好需要实现树最大深度的方法,这个方法主要是比较和值的向上传递。
解法:
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}else{
return isBalanced(root.left)&&isBalanced(root.right)&&Math.abs(height(root.left)-height(root.right))<2;
}
}
public int height(TreeNode root){
if(root==null){
return 0;
}else{
return 1+Math.max(height(root.left),height(root.right) );
}
}
}
具有所有最深节点的最小子树
题目:
分析:这题的关键也是找到当前树和子树的递推关系。这里的递推关系是:往深度更深的子树那边递归,当root的左右子树深度相同时,那么当前节点就是要求的节点了。这题和上一题的相同之处在于它们都要实现深度判断的方法,关于深度的判断,主要是最大深度的比较和向上传递,每传递一次累加1,这是一个以int为返回值的方法。
解法:
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
if(root==null){
return null;
}
int leftHeight=height(root.left);
int rightHeight=height(root.right);
if(leftHeight>rightHeight){
return subtreeWithAllDeepest(root.left);
}else if(leftHeight<rightHeight){
return subtreeWithAllDeepest(root.right);
}else{
return root;
}
}
public int height(TreeNode root){
if(root==null){
return 0;
}else{
return 1+Math.max(height(root.left),height(root.right));
}
}
}