1、求二叉树的宽度
答:基于层次遍历的cpp代码如下:
int TreeWidth(BinaryTreeNode *root)
{
int maxWidth = 0;
int currentWidth;
std::deque<BinaryTreeNode *> nodes;
BinaryTreeNode *currentNode;
if (root == NULL)
{
return 0;
}
nodes.push_back(root);
while (!nodes.empty())
{
currentWidth = nodes.size();
if (currentWidth > maxWidth)
{
maxWidth = currentWidth;
}
/* 当前层次节点出队,下一层次节点入队 */
while (currentWidth--)
{
currentNode = nodes.front();
nodes.pop_front();
if (currentNode->left)
{
nodes.push_back(currentNode->left);
}
if (currentNode->right)
{
nodes.push_back(currentNode->right);
}
}
}
return maxWidth;
}
二叉树的宽度定义为具有最多结点数的层中包含的结点数。
比如上图中,
第1层有1个节点,
第2层有2个节点,
第3层有4个节点,
第4层有1个节点,
可知,第3层的结点数最多,所以这棵二叉树的宽度就是4
2、求二叉树的叶节点数
答:
int TreeLeaves(BinaryTreeNode *root)
{
if (root == NULL)
{
return 0;
}
if (root->left == NULL && root->right == NULL)
{
return 1;
}
return TreeLeaves(root->left) + TreeLeaves(root->right);
}
3、求二叉树的深度
答:
int TreeDepth(BinaryTreeNode *root)
{
if (!root)
return 0;
int left;
int right;
left = TreeDepth(root->left);
right = TreeDepth(root->right);
return (left > right) ? (left + 1) : (right + 1);
}