题目
给定二叉树的根节点root,求二叉树的高度。
分析实现
一种方法是使用改进后的层次遍历,在遍历的过程中顺边记录得出二叉树的高度。
具体实现如下:
// 分层输出的层次遍历
int levelOrder(BTNode* root) {
if (root == NULL)
return 0;
queue<BTNode*> q;
q.push(root);
// 定义变量记录当前层次
int layer = 0;
while (!q.empty()) {
layer++;
// 定义变量记录当前层次结点个数
int n = q.size();
while (n--) {
BTNode* cur = q.front();
q.pop();
if (cur->left != NULL)
q.push(cur->left);
if (cur->right != NULL)
q.push(cur->right);
}
}
return layer;
}
但对于单纯的求二叉树的高度,可以采用递归的思想。利用后序遍历,通过子树的高度,轻松地得到二叉树的高度。
具体实现如下:
#include <algorithm>
// DFS
int getDepth(BTNode* root) {
if(!root)
return 0;
int dLeft = getDepth(root->left);
int dRight = getDepth(root->right);
return max(dLeft, dRight)+1;
}
总结
以上就是通过层次遍历和DFS中的后序遍历得到二叉树高度的实现。具体选用那种方案需根据题目要求,进行分析选择。