题目一:
输入一棵二叉树的根结点,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
关键词:二叉树的遍历
class Solution
{
public:
int treeDepth( TreeNode* pRoot )
{
if ( pRoot == NULL )
return 0;
int left = treeDepth( pRoot->left );
int right = treeDepth( pRoot->right );
return ( left > right ) ? ( left+1 ) : ( right+1 );
}
};
题目二:
输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
关键词:遍历二叉树
class Solution
{
public:
bool IsBalanced_Solution( TreeNode* pRoot )
{
int depth = 0;
return IsBalanced( pRoot, &depth );
}
bool IsBalanced( TreeNode* pRoot, int* pDepth )
{
if ( pRoot == NULL )
{
*pDepth = 0;
return true;
}
int left, right;
if ( IsBalanced( pRoot->m_pLeft, &left )
&& IsBalanced( pRoot->m_pRight, &right ))
{
int diff = left - right;
if ( diff <= 1 && diff >= -1 )
{
*pDepth = 1 + ( left > right ? left : right );
return true;
}
}
return false;
}
};