【LectCode】513. Find Bottom Left Tree Value

来源:互联网 发布:数据挖掘概念与技术 编辑:程序博客网 时间:2024/05/23 14:19

题目:

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

解题思路:用一个队列来存储树的节点,用一个整数count来计数树的当前层的节点数,依次遍历队列中当前层的树的节点,将当前节点的值赋值给num,若其子节点存在,则按照先右节点,后左节点的顺序将其子节点加入队列中,删除当前节点,则队列中最后剩下的那个节点则是所求。


解答:

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

return num;
}
    }
};