llllmz

导航

513. 找树左下角的值c

用的层序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int findBottomLeftValue(struct TreeNode* root) {
    if(!root->left&&!root->right) return root->val;
    struct TreeNode* queue[20000]={0};
    int front=0,tail=0;
    queue[tail++]=root;
    int end=0;
    int n=0;
    int x;
    while(front!=tail){
        struct TreeNode* temp=queue[front];
        n++;
        if(n==1) x=temp->val;
        if(front==end){
            if(temp->left) queue[tail++]=temp->left;
            if(temp->right) queue[tail++]=temp->right;
            end=tail-1;
            n=0;
        }else{
            if(temp->left) {
                queue[tail++]=temp->left;
            }
            if(temp->right) {
                queue[tail++]=temp->right;
            }
        }
        front++;
    }
    return x;
}

结果:

posted on 2024-03-05 22:01  神奇的萝卜丝  阅读(11)  评论(0)    收藏  举报