一. 二叉树的深度
题目:输入一个二叉树,从根节点到叶子节点的一条最长路径,这条路径的最长长度就是二叉树的深度。
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);
}