110. Balanced Binary Tree(五星,二叉树)

这个题简直了,不知道我是浮躁还是太累,错了四次。。。。。

给定二叉树,决定它是否高度平衡。在该问题中,高度平衡的二叉树是指任何节点的两个子树深度差不超过1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.


方法一:来自benlong

class solution {
public:
int dfsHeight (TreeNode *root) {
        if (root == NULL) return 0;
        
        int leftHeight = dfsHeight (root -> left);
        if (leftHeight == -1) return -1;
        int rightHeight = dfsHeight (root -> right);
        if (rightHeight == -1) return -1;
        
        if (abs(leftHeight - rightHeight) > 1)  return -1;
        return max (leftHeight, rightHeight) + 1;
    }
    bool isBalanced(TreeNode *root) {
        return dfsHeight (root) != -1;
    }
};


方法二:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    boolean result = true;
    public boolean isBalanced(TreeNode root) {
treeHeight(root);
        return result;
}
    
    public int treeHeight(TreeNode root){
        if (root == null)
return 0;
else {
            int left=treeHeight(root.left);
            int right=treeHeight(root.right);
if (Math.abs(left-right)> 1){
result = false;}
return Math.max(left, right) + 1;
}
    }

}


倒数第二次提交,我犯了一个特别简单的错误,如下加粗部分,使得递归过程重复进行两次,提交超时!

if (root == null)

    return 0;

else {

    if (Math.abs(treeHeight(root.left) - treeHeight(root.right)) > 1)

result = false;

    return Math.max(treeHeight(root.left), treeHeight(root.right)) + 1;

    }


还有一种O(n2)的方法,贴在下面,来自

class solution {
public:
    int depth (TreeNode *root) {
        if (root == NULL) return 0;
        return max (depth(root -> left), depth (root -> right)) + 1;
    }

    bool isBalanced (TreeNode *root) {
        if (root == NULL) return true;
        
        int left=depth(root->left);
        int right=depth(root->right);
        
        return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_39525565/article/details/80229605