美文网首页
513. Find Bottom Left Tree Value

513. Find Bottom Left Tree Value

作者: caisense | 来源:发表于2018-01-22 23:30 被阅读0次

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.

思路:和637. Average of Levels in Binary Tree
(https://www.jianshu.com/p/814d871c5f6d)的思路差不多,都是层遍历,若要返回最后一层最左侧叶节点,只需相反顺序遍历即可,637题目中的解法是先左子后右子,本题反过来,先右后左,则层遍历最后访问的一定是最后一层最左叶子,直接返回即可.

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> q; //节点队列
        q.push(root); //根先入队
        TreeNode* tmp; //层遍历工作节点
        while(!q.empty()) { //每次循环处理一层
            tmp = q.front();
            q.pop();
            //先右后左
            if (tmp->right) q.push(tmp->right);
            if (tmp->left) q.push(tmp->left);
        }
        return tmp->val; //循环访问的最后一个结点一定是最底层最左
    }
};

相关文章

网友评论

      本文标题:513. Find Bottom Left Tree Value

      本文链接:https://www.haomeiwen.com/subject/uvxdaxtx.html