树高(最大深度)延伸的递归题

1. 求树高(最大深度):
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

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

2. 根据树高是否满足Math.abs(leftHeight - rightHeight) <= 1,判断AVL树:

自底向上,先递归,再做当前节点的操作,类似于后序遍历,左右中。

写法一:如果以根节点为头节点的树的height不是-1,那么他是平衡的。
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) return -1; 意思是如果左子树是不平衡的或右子树是不平衡的或左右子树高度差大于1,这棵以head为头节点的树都是不平衡的,记为-1。

public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;//如果以根节点为头节点的树的height不是-1,那么他是平衡的
    }

    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = height(root.left);//得到左子树的高度
        int rightHeight = height(root.right);//得到右子树的高度
        if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
            return -1; //左子树或右子树或左右子树高度差大于1,这棵树都是不平衡的,记为-1
        } else {
            return Math.max(leftHeight, rightHeight) + 1;//如果这棵树平衡,那么返回他的高度
        }
    }

写法二:其实比”求树的高度“这题就多了if (Math.abs(right - left) > 1) res = false;这一行代码,外加定义一个全局变量res并返回res。

public class BalancedBinaryTree {
    boolean res = true; //全局变量

    public boolean isBalanced(TreeNode root) {

        helper(root);//求这棵树的高度
        return res;

    }

    private int helper(TreeNode root) {
        if (root == null) return 0;
        int left = helper(root.left);
        int right = helper(root.right);
        if (Math.abs(right - left) > 1) res = false;//有一个子树不是平衡的,那么res就是false
        return Math.max(left, right) + 1;
    }
}

  1. 根据树高,求两节点的最长路径

max = Math.max(max, leftDepth + rightDepth);

将某head节点的左右子树的高度(最大深度)加起来,即为以head为头节点的树的两节点(一个来自左子树,一个来自右子树)间最长路径。与之前记录过的最大深度(两节点来自左子树的左右子树或右子树的左右子树)最大值比较,若max大,保留max,若新值大,记录新值。

private int max = 0;

public int diameterOfBinaryTree(TreeNode root) {
    depth(root);
    return max;
}

private int depth(TreeNode root) {
    if (root == null) return 0;
    int leftDepth = depth(root.left);
    int rightDepth = depth(root.right);
    max = Math.max(max, leftDepth + rightDepth);//将某head节点的左右子树的高度(最大深度)加起来,即为以head为头节点的树的两节点(一个来自左子树,一个来自右子树)间最长路径。与之前记录过的最大深度(两节点来自左子树的左右子树或右子树的左右子树)最大值比较,若max大,保留max,若新值大,记录新值。
    return Math.max(leftDepth, rightDepth) + 1;//求树高(树最大深度)
}

reference:代码来自leetcode对应题目

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值