找树左下角的值
题目描述
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
解题思路
层次遍历二叉树,然后把每层第一个值赋给ans,直到遍历到最后一层的最左边的值。
题解
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int ans;
if(!root){
return ans;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int n = q.size();
for(int i = 0; i < n; i++){
TreeNode* cur = q.front();
q.pop();
if(i == 0){
ans = cur->val;
}
if(cur->left){
q.push(cur->left);
}
if(cur->right){
q.push(cur->right);
}
}
}
return ans;
}
};
390

被折叠的 条评论
为什么被折叠?



