LeetCode 平衡二叉树

版权声明:欢迎提问:[email protected] https://blog.csdn.net/include_heqile/article/details/82229750

https://leetcode-cn.com/problems/balanced-binary-tree/description/

我的解决方案:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int depth(TreeNode root) {
        if(root==null) return 0;
        int res = 1;
        return 1+Integer.max(depth(root.left),depth(root.right));
    }
    public boolean isBalanced(TreeNode root) {
        //这道题应该也是使用递归来做
        //计算左右子树的深度
        if(root==null) return true;
        if(Math.abs(depth(root.left)-depth(root.right))>1)
            return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }
}

我提交的时候,耗时是当前最短的

猜你喜欢

转载自blog.csdn.net/include_heqile/article/details/82229750