给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root){
if (root == NULL) {
return 0;
}
int left = maxDepth(root->left) + 1;
int right = maxDepth(root->right) + 1;
return left >= right ? left : right;
}
BFS
BFS,创建数组充当队列,按层遍历放入数组中。不过题目中未指明二叉树范围,所以数组的大小不好确认
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define Max_Node_Num 10000
struct TreeNode *tree_queue[Max_Node_Num];
int maxDepth(struct TreeNode* root){
int depth = 0;
int top = 0;
int tail = 1;//当前层的node数量
tree_queue[0] = root;
if(root==NULL){
return 0;
}
while(top<tail){
depth++;
int tmp = tail;//存储已遍历的node数量
int curlen = tail;//当前层的node数量
for(int i=top;i<curlen;i++){//遍历层
if(tree_queue[i]->left){
tree_queue[tail++] = tree_queue[i]->left;
}
if(tree_queue[i]->right){
tree_queue[tail++] = tree_queue[i]->right;
}
}
top = tmp;
}
return depth;
}