题目
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
分析
这一题是比较基础计算二叉树深度的题目。这一题可以分成递归与非递归两种解题思路。
首先是递归求解二叉树深度的解题思路:
- 当根节点为空是直接返回0;
- 否则,递归计算左子树和右子树高度,并得到两者最大值,返回最大值加1即可。
接下来是非递归求解二叉树深度的解题思路:
- 当根节点为空是直接返回0;
- 否则初始化队列,利用层次遍历来计算二叉树深度,初始化深度depth=0。首先将根节点入队;
- 当队列不为空时,depth加1,计算当前队列容量size,循环size次,依次将队首元素出队,并将队首元素非空左右子树入队。
github链接:JZ38-二叉树的深度
C++ 代码
1 递归解法代码
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL){
return 0;
}
int left_depth = this->TreeDepth(pRoot->left);
int right_depth = this->TreeDepth(pRoot->right);
return max(left_depth,right_depth)+1;
}
};
TreeNode* Create_BinaryTree()
{
TreeNode* T = new TreeNode(0);
char ch;
cin>>ch;
if(ch == '#'){ //“#”是结束标志
T = NULL;
}else{
T->val = int(ch); //对当前结点初始化
T->left = Create_BinaryTree(); //递归构造左子树
T->right = Create_BinaryTree(); //递归构造右子树
}
return T;
}
int main()
{
while(true){
TreeNode* root = Create_BinaryTree();
Solution s;
cout<<s.TreeDepth(root);
}
return 0;
}
2 非递归解法代码
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <queue>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL){
return 0;
}
queue<TreeNode*> q;
TreeNode* front = pRoot;
TreeNode* last = pRoot;
int depth = 0;
q.push(pRoot);
while(!q.empty()){
depth++;
int size = q.size();
while(size--){
TreeNode* node = q.front();
q.pop();
if(node->left){
q.push(node->left);
}
if(node->right){
q.push(node->right);
}
}
}
return depth;
}
};
TreeNode* Create_BinaryTree()
{
TreeNode* T = new TreeNode(0);
char ch;
cin>>ch;
if(ch == '#'){ //“#”是结束标志
T = NULL;
}else{
T->val = int(ch); //对当前结点初始化
T->left = Create_BinaryTree(); //递归构造左子树
T->right = Create_BinaryTree(); //递归构造右子树
}
return T;
}
int main()
{
while(true){
TreeNode* root = Create_BinaryTree();
Solution s;
cout<<s.TreeDepth(root);
}
return 0;
}