简单
相关标签
相关企业
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入: root = [3,9,20,null,null,15,7]
输出: 3
示例 2:
输入: root = [1,null,2]
输出: 2
提示:
- 树中节点的数量在
[0, 104]区间内。 -100 <= Node.val <= 100
题解:
bug:TreeNode* root, lc, rc;1. 变量声明方式不正确,TreeNode* root, lc, rc; 这样声明会导致lc和rc被声明为TreeNode类型而非指针类型
递归深度搜索获取树的深度时候,深度变量不能直接传递,不然递归时候同高度每个节点递归都会给深度加1,所以深度值只能从上一层传下来的整型变量值depth去加一,然后再设一个ans,这个用int* ans,需要从头传到尾,保存ans和depth的最大值。(由于depth是从上一层给出来的整形变量,不会修改上面的值,depth也是当前深度)
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode{
int val;
struct TreeNode* lchild;
struct TreeNode* rchild;
} TreeNode;
int max(int a, int b)
{
return a >= b?a:b;
}
void dfs(TreeNode* root, int *ans, int depth)
{
if (root == NULL)
{
return;
}
depth ++;
*ans = max(*ans, depth);
dfs(root->lchild, ans, depth);
dfs(root->rchild, ans, depth);
return;
}
int main()
{
// TreeNode queue[10000];
// int bottom = -1, top = -1;
TreeNode* root;
int ans = 0, depth = 0;
TreeNode* ro = NULL;
TreeNode* lc = NULL;
TreeNode* rc = NULL;
root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 3;
root->lchild = (TreeNode*)malloc(sizeof(TreeNode));
lc = root->lchild;
lc->val = 9;
lc->lchild = NULL;
lc->rchild = NULL;
root->rchild = (TreeNode*)malloc(sizeof(TreeNode));
rc = root->rchild;
rc->val = 20;
ro = rc;
ro->lchild = (TreeNode*)malloc(sizeof(TreeNode));
lc = ro->lchild;
lc->val = 15;
lc->lchild = NULL;
lc->rchild = NULL;
ro->rchild = (TreeNode*)malloc(sizeof(TreeNode));
rc = ro->rchild;
rc->val = 7;
rc->lchild = NULL;
rc->rchild = NULL;
dfs(root, &ans, depth);
printf("%d", ans);
return 0;
}