• 513. Find Bottom Left Tree Value


    问题:

    求给定二叉树,最底层最左边的节点值。

    Example 1:
    Input: root = [2,1,3]
    Output: 1
    
    Example 2:
    Input: root = [1,2,3,4,null,5,6,null,null,7]
    Output: 7
     
    Constraints:
    The number of nodes in the tree is in the range [1, 104].
    -231 <= Node.val <= 231 - 1
    

      

    example 1:

    example 2:

    解法:BFS

    queue:存储每层节点,从左向右left->right

    每次处理每层节点前,保存第一个节点作为res

    最后所有queue节点处理完成。

    得到的res即为,最后一层第一个(最左边)节点。

    代码参考:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10  * };
    11  */
    12 class Solution {
    13 public:
    14     int findBottomLeftValue(TreeNode* root) {
    15         int res = 0;
    16         queue<TreeNode*> q;
    17         if(root) q.push(root);
    18         while(!q.empty()) {
    19             int sz = q.size();
    20             res = q.front()->val;
    21             for(int i=0; i<sz; i++) {
    22                 TreeNode* cur = q.front();
    23                 q.pop();
    24                 if(cur->left) q.push(cur->left);
    25                 if(cur->right) q.push(cur->right);
    26             }
    27         }
    28         return res;
    29     }
    30 };
  • 相关阅读:
    json_decode 转数组
    json_encode转义中文问题
    ECshop后台新功能权限添加
    mysql中int、bigint、smallint 和 tinyint的区别与长度的含义
    mysql数据库表设计小数类型
    mysql group_concat用法
    PHP socket通信之UDP
    本地tp项目上传服务器报runtime/cache错误
    mysql 命令一套
    linux 9 -- 交互式使用Bash Shell
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14473739.html
Copyright © 2020-2023  润新知