1. 程式人生 > >LC 513. Find Bottom Left Tree Value

LC 513. Find Bottom Left Tree Value

1.題目

513. Find Bottom Left Tree Value

Medium

46477

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

    2
   / \
  1   3

Output:
1

 

Example 2: 

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

 

Note: You may assume the tree (i.e., the given root node) is not NULL.

 

2.解題思路

用BFS一層層從左到右搜尋,儲存每層第一個值。最後一個儲存的值即為要求。

 

3.程式碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        int result = root->val;
        queue<TreeNode*> q;//用佇列進行BFS儲存每一行資料
        q.push(root);//第一行進入佇列
        while(!q.empty()) {
            int size = q.size();
            result = q.front()->val;//BFS是從左到右進行的,所以result存入的是隊頭數值
            while(size--) {//這一層結束。下一層進入並讓這一層出隊
                if (q.front()->left!=NULL) {q.push(q.front()->left);}//加入下一層
                if (q.front()->right!=NULL) {q.push(q.front()->right);}//加入下一層
                q.pop();//隊頭元素出隊
            }
        }
        return result;
    }
};