二叉树数据结构声明:
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
};
1、递归求二叉树深度
int getDepth(TreeNode *root)
{
if (root == NULL)
{
return 0;
}
return getDepth(root->left) > getDepth(root->right) ?(getDepth(root->left) + 1) : (getDepth(root->right) + 1);
}
2、宽度优先遍历求二叉树宽度
宽度优先遍历,记录每一个层次的叶子节点,返回最大值
int getWidth(TreeNode *root)
{
if (root == NULL)
{
return 0;
}
int width_up = 0;
int temp = 0;
int width_cur = 0;
int width_res = 0;
queue<TreeNode *> myQueue;
myQueue.push(root);
width_up = 1;
width_res=1;
TreeNode *temp_TreeNode = NULL;
while (!myQueue.empty())
{
temp = width_up