LeetCode Find Bottom Left Tree Value

LeetCode Find Bottom Left Tree Value 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.
找出一棵二叉树最后一行的最左边元素。 简单题,直接BFS,每层保存队列第一个元素,BFS结束之后,就能得到最后一行的第一个元素。 代码如下: [cpp] class Solution { public: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> q; q.push(root); int ans = 0; while (!q.empty()) { int n = q.size(); ans = q.front()->val; while (n–) { TreeNode* front = q.front(); q.pop(); if (front->left)q.push(front->left); if (front->right)q.push(front->right); } } return ans; } }; [/cpp] 本代码提交AC,用时12MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *