简体   繁体   English

二叉树级订单遍历LeetCode

[英]Binary Tree Level Order Traversal LeetCode

Well this one question is from LeetCode. 这个问题来自LeetCode。 The question is to find the left most node of the last level of the tree. 问题是要找到树最后一级的最左侧节点。 I tried it using a simple level order traversal by keeping one extra pointer for tracking the first element of each level(which will of course be the left most element). 我通过保留一个额外的指针来跟踪每个级别的第一个元素(当然将是最左边的元素),使用简单的级别顺序遍历进行了尝试。

While the code runs perfectly fine on my machine. 虽然代码在我的机器上运行得很好。 It shows a different output in leetcode judge. 它在leetcode判断器中显示了不同的输出。 Here is my code 这是我的代码

int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*>q;
q.push(root);
q.push(NULL);
TreeNode*first;

while(!q.empty())
{
   TreeNode*temp = q.front();
   q.pop();
   if(temp==NULL)
   {
     if(q.front()!=NULL)
       first = q.front();
     if(!q.empty())
        q.push(NULL);
    }
    else
    {
      if(temp->left)
      {
        q.push(temp->left);
      }
      if(temp->right)
      {
         q.push(temp->right);
      }
     }
    }
    return first->val;
}

For detailed analysis of the question visit https://leetcode.com/problems/find-bottom-left-tree-value/#/description 有关问题的详细分析,请访问https://leetcode.com/problems/find-bottom-left-tree-value/#/description

For the given test case [2,1,3] my code is giving the output 0 while the correct output is 1. 对于给定的测试用例[2,1,3],我的代码给出的输出为0,而正确的输出为1。

Any help is appreciated. 任何帮助表示赞赏。

At this point: 这一点:

  if(q.front()!=NULL)

you do not know if there is anything in the queue. 您不知道队列中是否有任何内容。 You should be testing wirth q.empty() before using q.front() . 您应该测试沃思q.empty()使用前q.front() Your program therefore is exhibiting undefined behaviour. 因此,您的程序表现出不确定的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM