【问题标题】:Check If Binary Tree Is Balanced [closed]检查二叉树是否平衡[关闭]
【发布时间】:2021-09-24 08:06:54
【问题描述】:

这是我的错误答案。我还在对递归感到困惑,为什么我不能把true和false放在一起,而不是把true放在开头?

public class Solution {
  public boolean isBalanced(TreeNode root) {    
    int left = findHeight(root.left);
    int right = findHeight(root.right);
    if (Math.abs(left-right) <= 1) {
      return true;
    } else {
      return false;
    } 
    return (isBalanced(root.left)&&isBalanced(root.right));

  }
  private int findHeight(TreeNode root) {  
    if (root == null) {
      return 0;
    }
    return Math.max(findHeight(root.left), findHeight(root.right)) + 1;
  }
}

这是正确的答案。

public boolean isBalanced(TreeNode root) {
    if (root==null) {
      return true;
    }
    int leftHeight = findHeight(root.left);
    int rightHeight = findHeight(root.right);
    if(Math.abs(leftHeight-rightHeight)>1) {
      return false;
    } 
    return isBalanced(root.left)&&isBalanced(root.right);
  }

【问题讨论】:

  • return (isBalanced(root.left)&amp;&amp;isBalanced(root.right)); 将永远没有机会执行

标签: java recursion binary-tree


【解决方案1】:

if (Math.abs(left-right) &lt;= 1) { return true; } else { return false; } 将始终为return 某事,这意味着您将永远无法进行递归调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多