题目
![](https://img-blog.csdnimg.cn/img_convert/246b48471e23d4aac65e1202a55909ce.png)
题解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//最大队列长度
#define MAXSIZE 5000
//层次遍历结构
typedef struct QueueNode{
struct TreeNode * val;
int floor;
}QueueNode,*Queue;
int findBottomLeftValue(struct TreeNode* root){
//层序遍历队列预备工作
Queue q = (QueueNode*)malloc(sizeof(QueueNode)*MAXSIZE);
int rear = 0,front = 0;
q[rear].val = root;
q[rear].floor = 1;
rear = (rear+1) % MAXSIZE;
//结果存储在result中
QueueNode result = q[front];
//遍历循环队列
while(front != rear){
QueueNode temp = q[front];
front = (front+1) % MAXSIZE;
if(temp.floor > result.floor){
result = temp;
}
if(temp.val->left != NULL){
q[rear].val = temp.val->left;
q[rear].floor = temp.floor+1;
rear = (rear+1) % MAXSIZE;
}
if(temp.val->right != NULL){
q[rear].val = temp.val->right;
q[rear].floor = temp.floor+1;
rear = (rear+1) % MAXSIZE;
}
}
return result.val->val;
}
![](https://img-blog.csdnimg.cn/img_convert/6a0108b4326acb10ce0b174a3d0b7567.png)
要点
犯了一个错误,MAXSIZE想设置成题目可能最大结点的一半,应该直接设置成值,不要设置成表达式
#define MAXSIZE 10000/2 //错误
#define MAXSIZE 5000 //正确
结构值A赋值给B,只是结构属性一样,地址不一样。
typedef struct Node{
int val;
int floor;
}Node;
int main()
{
Node a = {10,20};
Node b = a;
}
//得到b.val == a.val;b.floor == a.floor;&b != &a;
看题解有深度遍历优先。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth = -1;
int leftval = 0;
void dfs(struct TreeNode* root, int depth) {
if (root == NULL)
return -1;
if (depth > maxDepth) {
maxDepth = depth;
leftval = root->val;
}
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
return;
}
int findBottomLeftValue(struct TreeNode* root){
maxDepth = -1;
leftval = 0;
dfs(root, 1);
return leftval;
}
速度慢点,但思路清晰易写。
![](https://img-blog.csdnimg.cn/img_convert/98972c3b7e9b863367a258bc5b8aa133.png)