6

LeetCode 第 102 号问题:二叉树的层序遍历

 3 years ago
source link: https://www.cxyxiaowu.com/6874.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
LeetCode 第 102 号问题:二叉树的层序遍历-程序员小吴
当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 102 号问题:二叉树的层序遍历

本文首发于公众号「五分钟学算法」,是图解 LeetCode 系列文章之一。

个人网站:https://www.cxyxiaowu.com

题目来源于 LeetCode 上第 102 号问题:二叉树的层序遍历。题目难度为 Medium,目前通过率为 55.8% 。

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

该问题需要用到队列

  • 建立一个queue
  • 先把根节点放进去,这时候找根节点的左右两个子节点
  • 去掉根节点,此时queue里的元素就是下一层的所有节点
  • 用for循环遍历,将结果存到一个一维向量里
  • 遍历完之后再把这个一维向量存到二维向量里
  • 以此类推,可以完成层序遍历
2elr5.gif
/// BFS
/// Time Complexity: O(n), where n is the number of nodes in the tree
/// Space Complexity: O(n)
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {

vector<vector<int>> res;
        if(root == NULL)
            return res;

queue<pair<TreeNode*,int>> q;
        q.push(make_pair(root, 0));

while(!q.empty()){

TreeNode* node = q.front().first;
            int level = q.front().second;
            q.pop();

if(level == res.size())
                res.push_back(vector<int>());
            assert( level < res.size() );

res[level].push_back(node->val);
            if(node->left)
                q.push(make_pair(node->left, level + 1 ));
            if(node->right)
                q.push(make_pair(node->right, level + 1 ));
        }

return res;
    }
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK