力扣刷题-513.找树左下角的值

题目

题解

/**
 * 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;
}

要点

  1. 犯了一个错误,MAXSIZE想设置成题目可能最大结点的一半,应该直接设置成值,不要设置成表达式

#define MAXSIZE 10000/2 //错误
#define MAXSIZE 5000    //正确
  1. 结构值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;
  1. 看题解有深度遍历优先。

/**
 * 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;
}

速度慢点,但思路清晰易写。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东东咚咚东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值