面试题39:二叉树的深度&平衡二叉树的判断

一. 二叉树的深度

题目:输入一个二叉树,从根节点到叶子节点的一条最长路径,这条路径的最长长度就是二叉树的深度。

public int Depth(TreeNode root) {
        if(root == null)return 0;
        int left = 1+Depth(root.left);
        int right = 1+Depth(root.right);
	    return left>right?left:right;
    }

二. Minimum Depth of Binary Tree(Leetcode-111)

最小深度的定义:根节点到最近的叶子结点的路径上的节点数目

递归求最小深度,左右子树高度的最小值为二叉树的最小高度。

特殊情况:如果左右子数有空的情况(也就是左右高度有=1的情况下,取最大值),最小深度就是非空子数的深度。

int minDepth(TreeNode* root) {
        if(root == NULL)
        {
            return 0;
        }
        
        int left_depth = 1+minDepth(root->left);
        int right_depth = 1+minDepth(root->right);
        if(left_depth == 1 || right_depth == 1)
        {
            return left_depth<right_depth?right_depth:left_depth;
        }
        return left_depth>right_depth?right_depth:left_depth;
    }

三. 判断平衡二叉树(Leetcode-110)

平衡二叉树(AVL)概念:二叉树中每个节点的左子树的高度与右子树的高度绝对值不超过1;
也就是说每个节点的左子树和右子树都是平衡二叉树。

思路:递归,前提是先写出求二叉树高度的函数
然后遍历二叉树,求每个节点的左右子树的高度,高度差>1,返回false
再递归调用本函数,检查左右子树是否都是平衡二叉树

int MaxDepth(TreeNode* pRoot) {
  if (pRoot == nullptr) {
    return 0;
  }
  int left = 1 + MaxDepth(pRoot->left);
  int right = 1 + MaxDepth(pRoot->right);
  return left > right ? left : right;
}

bool IsBalanced_Solution(TreeNode* pRoot) {
  if (pRoot == nullptr) {
    return true;
  }
  int left_depth = MaxDepth(pRoot->left);
  int right_depth = MaxDepth(pRoot->right);
  if (abs(left_depth - right_depth) > 1) {
    return false;
  }
  return IsBalanced_Solution(pRoot->left) &&
         IsBalanced_Solution(pRoot->right);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值