感觉一写递归就全是错。
首先练熟递归,然后搞清楚dfs bfs与各种traversal关系,再写树
这个题首先一开始递归写的有问题,既然每次已进入helper函数,首先判断了node是否为空,就不要再继续先判断是否有左右子再递归了,直接递归就行。正确的:
public int countD ( TreeNode node){
if ( node == null)
return 0;
return Math.max(countD(node.left),countD(node.right))+1;
}
错误的:
public int countD ( TreeNode node){
if ( node == null)
return 0;
if ( node.left == null && node.right == null )
return 1;
int leftVal = 0;
int riVal = 0;
if ( node.left != null){
leftVal = countD(node.left);
}
if ( node.right != null){
riVal = countD(node.right);
}
return Math.max(leftVal,riVal)+1;
}
然后就是主函数调用也是一样,直接把root放入就行,不用判断左右是否null
最大的问题是假如只考虑左右子树的depth 而不考虑左右子树是否平衡,就会有问题,就是左右子树的depth虽然相等,但他们本身是不平衡的 所以最后的判断要继续递归isbalanced这个函数。
public class Solution {
public boolean isBalanced(TreeNode root) {
if ( root == null )
return true;
if ( root.left == null && root.right == null ){ //这个判断没有必要
return true;
}
boolean res = false;
int leftVal = countD(root.left);
int riVal = countD(root.right);
if ( Math.abs(leftVal-riVal) <= 1 && isBalanced(root.left) && isBalanced(root.right)){
res = true;
}
return res;
}
public int countD ( TreeNode node){
if ( node == null)
return 0;
return Math.max(countD(node.left),countD(node.right))+1;
}
}补充一点:一开始想的是,在判断某个子树的时候,假如它不平衡,那么整个树就不平衡了,直接就可以return false。本打算是用node.val记录高度,然后helper也是个返回bool的函数。
试了一下 发现自己傻了 不可能,因为即使返回了false 也只是返回上一层,还是要遍历的

本文讨论了递归算法在树结构深度计算中常见错误,并提供了优化建议。包括直接递归调用而非重复判断节点是否存在,以及正确处理不平衡树的情况。重点介绍了在不考虑树平衡性的前提下,如何准确计算树的深度。

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



