• (二叉树 BFS) leetcode513. 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,也可以用DFS,不过BFS相对会简单一些的。

    C++代码:

    /**
     * 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) return 0;
            queue<TreeNode*> q;
            q.push(root);
            int res = root->val;
            while(!q.empty()){
                int len = q.size();  //必须加上这个,如果用i==q.size(),则会出错,因为q.size()会变化。
                for(int i = len; i > 0; i--){
                    auto t = q.front();
                    q.pop();
                    if(i == len){
                        res = t->val;
                    }
                    if(t->left) q.push(t->left);
                    if(t->right) q.push(t->right);
                }
            }
            return res;
        }
    };
  • 相关阅读:
    2019 SDN上机第7次作业
    2019 SDN上机第六次作业
    2019 SDN上机第5次作业
    SDN课程阅读作业(2)
    2019 SDN上机第4次作业
    2019 SDN阅读作业
    2019 SDN上机第3次作业
    第09组 团队Git现场编程实战
    预习非数值数据的编码方式
    预习原码补码
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10716217.html
Copyright © 2020-2023  润新知