Leetcode 513.找树左下角的值

题目地址

思路

读完题干,立刻就想到用层序遍历来实现。
具体实现代码如下:

代码实现(C++)

class Solution {
    
    
public:
    int findBottomLeftValue(TreeNode* root) 
    {
    
    
        queue<TreeNode*> que;
        if(root==nullptr)
        {
    
    
            return 0;
        }
        que.push(root);
        vector<int> res;
        while(!que.empty())
        {
    
    
            int size=que.size();
            for(int i=0;i<size;i++)
            {
    
       
                
                TreeNode* node=que.front();
                if(i==0)
                {
    
    
                    res.push_back(node->val);
                }
                que.pop();
                if(node->left)
                {
    
    
                    que.push(node->left);
                }
                if(node->right)
                {
    
    
                    que.push(node->right);
                }
                
            }
        }
        return res[res.size()-1];
    }
};

总结

我用了一个数组把每一层的最左边的值都记录下来了,然后最后返回数组的最后一个值。
后来仔细想想,其实不用这么麻烦,直接每一个都覆盖res就好了。

猜你喜欢

转载自blog.csdn.net/weixin_45847364/article/details/122083192