xinyu04

导航

LeetCode 513 Find Bottom Left Tree Value BFS

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

Solution

要求出最后一层最左边的节点的值。做法很简单,首先判断是不是最后一层,如果不是,则将该层节点的子节点都 \(push\) 到队列中。

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    queue<TreeNode *> q;
public:
    int findBottomLeftValue(TreeNode* root) {
        if(!root->left && !root->right)return root->val;
        q.push(root);
        while(!q.empty()){
            int n = q.size();
            bool flag = true;// check if the last layer
            TreeNode* tmp;
            for(int i=0;i<n;i++){
                TreeNode *rt = q.front();q.pop();
                if(!rt->right && !rt->left){
                    if(i==0)tmp = rt;
                    continue;
                }
                else{
                    flag = false;
                    if(rt->left)q.push(rt->left);
                    if(rt->right)q.push(rt->right);
                }
            }
            if(flag)return tmp->val;
        }
        return -1;
    }
};

posted on 2022-06-01 03:35  Blackzxy  阅读(12)  评论(0编辑  收藏  举报