给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
与层序遍历迭代法相同
最后一层的第一个节点的值就是树左下角的值
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> qu;
if(root==NULL) return 0;
qu.push(root);
int flag=0;
int ff;
while(!qu.empty())
{
int k = qu.size();
ff = 0;
for(int i=0;i<k;i++)
{
TreeNode * t = qu.front();
qu.pop();
if(!t->left&&!t->right)
{
if(ff==0)
{
flag = t->val;
}
ff=1;
}
else
{
ff=0;
}
if(t->left) qu.push(t->left);
if(t->right) qu.push(t->right);
}
}
if(ff==1)
{
return flag;
}
return 0;
}
};
自己写的好憨, 存第一个节点就可以了
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
int result = 0;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (i == 0) result = node->val; // 记录最后一行第一个元素
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return result;
}
};