Leetcode102二叉树的层次遍历

2019-11-03  本文已影响0人  answerLDA

题目

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

例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]

代码及分析

/**
 * 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) {
        if(!root)
            return {};
        //用来装返回结果
        vector<vector<int>> res;
        //用来装每一层的结果
        vector<int> cell;
        //用来装每一个被遍历的节点
        vector<TreeNode*> list;
        //先把根节点放进去
        list.push_back(root);
        //nextNum是下一层的元素个数;nextCell是下一层的开始位置。
        int nextNum=0,nextCell=1;
        //遍历列表
        for(int i = 0;i<list.size();i++){
            TreeNode* p = list[i];
            //如果到了这一层的开始位置,就把上一层的结果放进res里面,
            //临时遍历重新清零,并更新下一层的开始位置
            if(i==nextCell){
                res.push_back(cell);
                cell = {};
                nextCell += nextNum;
                nextNum=0;
            }
            //把这一层的元素放进临时层列表
            cell.push_back(p->val);
            //把左右的元素放进去待遍历列表中,并对下一层元素个数进行计数
            if(p->left){
                list.push_back(p->left);
                nextNum++;
            }
             if(p->right){
                list.push_back(p->right);
                 nextNum++;
            }
        }
        //把最后一层放进去结果里面
        res.push_back(cell);
        return res;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读