#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
//5种情况:空树;没有子树;只有左/右子树;有俩子树;
struct BinaryNode {
BinaryNode *left;
BinaryNode *right;
int data;
};
struct BinaryTree {
BinaryNode *head;
};
//后序遍历递归
//如果左右子树都存在,则取其最小
//如果左右子树没有其中一个,-->说明此根下有叶子结点。所以取其最大
int getDepth(BinaryNode *node)
{
if (node == NULL)
return 0;
int left_depth = getDepth(node->left);
int right_depth = getDepth(node->right);
if (left_depth && right_depth) //左子树和右子树都存在
return min(left_depth, right_depth) + 1;
else
return max(left_depth, right_depth) + 1;
}
//层次遍历,使用队列完成
int getDepth2(BinaryNode *root)
{
if (root == NULL)
return 0;
queue<BinaryNode *>q;
q.push(root);
int depth = 0;
while (!q.empty()) //q存放当前层结点,qt存放下一层结点
{
queue<BinaryNode *>qt;
depth++;
while (!q.empty())
{
BinaryNode *temp = q.front();
cout << temp->data << endl;
q.pop();
if (!temp->left && !temp->right)
{
return depth;
}
if (temp->left)
qt.push(temp->left);
if (temp->right)
qt.push(temp->right);
}
q = qt;
}
return depth;
}
int main()
{
/*
7
/ \
8 9
/ \
4 10
/ \
2 5
*/
BinaryTree btree;
BinaryNode node1 = { NULL,NULL,7};
BinaryNode node2 = { NULL,NULL,9 };
BinaryNode node3 = { NULL,NULL,8 };
BinaryNode node4 = { NULL,NULL,4 };
BinaryNode node5 = { NULL,NULL,2 };
BinaryNode node6 = { NULL,NULL,5 };
BinaryNode node7 = { NULL,NULL,10 };
btree.head = &(node1);
node1.left = &(node3);
node1.right = &(node2);
node2.right = &(node7);
node3.left = &(node4);
node4.left = &(node5);
node4.right = &(node6);
int height = getDepth2(&(node1));
cout << height << endl;
}
运行结果: