LeetCode- Find Bottom Left Tree Value

来源:互联网 发布:linux 驱动与 win驱动 编辑:程序博客网 时间:2024/06/06 17:35
题目:

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

Example 1:

Input:    2   / \  1   3Output:1

Example 2: 

Input:        1       / \      2   3     /   / \    4   5   6       /      7Output:7

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

解读:给予一颗二叉树,找到最深的节点中最左边的那个并输出val值。

思考:采用BFS层次遍历算法,为使的最后的结果输出的是最左边的节点,则queue先push右节点再push左节点。

代码:

/** * 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) {        queue<TreeNode*> q;        int answer;        if(root != NULL)           q.push(root);        while(q.size()){            if(q.front()->right !=NULL)                q.push(q.front()->right);            if(q.front()->left !=NULL)                q.push(q.front()->left);            answer = q.front()->val;            q.pop();        }        return answer;    }};


原创粉丝点击