Leetcode_二叉树_理解

做有关于树的题目时,要注意模块化功能函数,注意联系之前学过的小知识点

如下面两题,判断一颗树是否为平衡二叉树建立在求二叉树的高度的基础上。

//求树的高度
public int depth(TreeNode root){
if(null == root){
return 0;
}
return Math.max(depth(root.left), depth(root.right)) + 1;
}

//判断一二叉树是否为平衡二叉树
public boolean isBalanced(TreeNode root) {
    if(null == root){
        return true;
    }

    return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}

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

Guess you like

Origin blog.csdn.net/weixin_48394650/article/details/120645666