二叉树的层次遍历

来源:互联网 发布:mysql having count 编辑:程序博客网 时间:2024/06/02 03:47

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

样例

给一棵二叉树 {3,9,20,#,#,15,7} :

  3 / \9  20  /  \ 15   7

返回他的分层遍历结果:

[  [3],  [9,20],  [15,7]]
解题思路:利用队列,先进先出的
/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */  class Solution {    /**     * @param root: The root of binary tree.     * @return: Level order a list of lists of integer     */public:    vector<vector<int>> levelOrder(TreeNode *root) {        // write your code here        vector<vector<int>> result;        if(root == NULL)        {            return result;        }        queue<TreeNode *>Q;        Q.push(root);        while(!Q.empty())        {            int size = Q.size();            vector<int> temp;            for (int i = 0; i < size; i++)            {                TreeNode *head = Q.front();Q.pop();                temp.push_back(head->val);                if (head->left)                {                    Q.push(head->left);                }                if (head->right)                {                    Q.push(head->right);                }            }            result.push_back(temp);        }        return result;    }};



0 0