LeetCode 102. Binary Tree Level Order Traversal 题解

来源:互联网 发布:华为 mac过滤 编辑:程序博客网 时间:2024/06/05 23:39

102. Binary Tree Level Order Traversal

 
 My Submissions
  • Total Accepted: 130184
  • Total Submissions: 365689
  • Difficulty: Easy
  • Contributors: Admin

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]]

解题思路:

本题即使用BFS即可,唯一注意一点的是使用precount记录每一层结点的个数。

代码展示

/** * 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>> res;        if(!root) return res;        queue<TreeNode*> tra;        tra.push(root);        //vector<int> v;        //v.push_back(root->val);        //res.push_back(v);        int precount=1;        int count =0;        while(tra.size())        {            //cout<<tra.size()<<endl;            vector<int> v;            while(precount--)            {                TreeNode * top = tra.front();                tra.pop();                if(top->left)                {                    tra.push(top->left);                    count++;                }                if(top->right)                {                    tra.push(top->right);                    count++;                }                v.push_back(top->val);                            }            if(v.size())            res.push_back(v);            precount = count;            count=0;                                }        return res;            }};

0 0
原创粉丝点击