LeetCode刷题笔记--102. Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

Medium

127132FavoriteShare

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

这道题理解上有点难,花了一点时间想通。网上文章很多,但一开始还是感觉无法理解。因为网上讲细节的很少,贴代码的居多。我把自己的理解详细记录下来,哪天忘了,看看就明白了。

先学习了queue,queue是先进先出(FIFO)的。查了一下c++官网:www.cplusplus.com,里面的解释如下:

FIFO queue

queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other.

queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front".

队列是一种容器适配器,专门设计用于在FIFO上下文(先进先出)中操作,其中元素插入容器的一端并从另一端提取。

队列作为容器适配器实现,这些类使用特定容器类的封装对象作为其基础容器,提供一组特定的成员函数来访问其元素。元素被推到特定容器的“后”中,并从其“前”弹出。

解题思路就是先把根节点push进queque这个容器,放入后,根节点就是这个queue的front。从front到end逐个处理queque中的treenode。拿根节点举例子,把根节点push进去后,queue容器中只有一个treenode,此时只需要把root的值取出来,压到最终要返回的vector中。压完后把root节点pop出来。这时queque中没有treenode了。然后我们来添加treenode,如果root->left有值,那么把root->left push到queque容器中,同样,如果root->right有值,那么把root->right push到queque容器中。然后重复,从front到end逐个处理queque中的treenode。知道queque容器中没有东西了。判断终止的条件就是queque.size()没有值了。

AC的代码如下:

/**
 * 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:    
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> y;
        y.clear();
        if(!root)return y;
        
        queue<TreeNode*> que;
        que.push(root);
        
        while(que.size())
        {
            int num=que.size();
            vector<int> x;
            x.clear();
            
            while(num>0)
            {
                TreeNode* t=que.front();
                x.push_back(t->val);
                que.pop();
                
                if(t->left)que.push(t->left);
                if(t->right)que.push(t->right);
                num--;
            }
            y.push_back(x);
            
        }
        return y;
        
        
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/88555561