问题:
求给定二叉树,最底层最左边的节点值。
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 };