「这是我参与11月更文挑战的第15天,活动详情查看:2021最后一次更文挑战」
110. 平衡二叉树
题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例 1:
输入: root = [3,9,20,null,null,15,7]
输出: true
示例 2:
输入: root = [1,2,2,3,3,null,null,4,4]
输出: false
示例 3:
输入: root = []
输出: true
递归法解析
使用后序遍历的递归方法,在递归的过程中判断树是否是平衡二叉树,如果不是直接返回-1,是的话返回树的高度。 算法步骤:
- 判断递归函数的参数以及返回值
- 判断递归函数的终止条件
- 确定单层递归的逻辑
递归法
class Solution
{
public:
bool isBalanced(TreeNode *root)
{
return getDepth(root) == -1 ? false : true;
}
// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树,则返回-1
int getDepth(TreeNode *root)
{
if (root == NULL)
{
return 0;
}
// 求左子树的高度
int leftDepth = getDepth(root->left); // 左
// 说明左子树已经不是平衡二叉树
if (leftDepth == -1)
{
return -1;
}
// 求右子树的高度
int rightDepth = getDepth(root->right); // 右
// 说明右子树不是平衡二叉树
if (rightDepth == -1)
{
return -1;
}
// 如果时平衡二叉树,则返回其高度,否则返回-1
return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
}
};
迭代法解析
通过栈模拟后序遍历,找每一个节点的高度 算法步骤
- 定义求高度的函数
getDepth - 根据
getDepth函数的返回的值判断树是否是平衡二叉树
迭代法
// 迭代法
// 通过栈模拟后序遍历,来找到每一个节点的高度,(通过求传入的节点作为根节点的最大深度来求高度)
class Solution1
{
bool isBalanced(TreeNode *root)
{
stack<TreeNode *> st;
if (root == NULL)
{
return true;
}
st.push(root);
while (!st.empty())
{
TreeNode *node = st.top();
st.pop();
// 判断左右子树的高度差是否大于1
if (abs(getDepth(node->left) - getDepth(node->right)) > 1)
{
return false;
}
if (node->right)
st.push(node->right); // 右(空节点不入栈)
if (node->left)
st.push(node->left); // 左(空节点不入栈)
}
return true;
}
// 利用层序遍历求深度
// cur节点的最大深度就是cur的高度
int getDepth(TreeNode *cur)
{
stack<TreeNode *> st;
if (cur != NULL)
{
st.push(cur);
}
// 深度
int depth = 0;
int result = 0;
while (!st.empty())
{
TreeNode *node = st.top();
if (node != NULL)
{
st.pop();
// 中
st.push(node);
st.push(NULL);
depth++;
// 右
if (node->right)
{
st.push(node->right);
}
// 左
if (node->left)
{
st.push(node->left);
}
}
else
{
st.pop();
node = st.top();
st.pop();
depth--;
}
result = result > depth ? result : depth;
}
return result;
}
};