LintCode 二叉树的层次遍历

题目描述:

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

您在真实的面试中是否遇到过这个题? Yes
样例
给一棵二叉树 {3,9,20,#,#,15,7} :

3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:

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

思路分析:

bfs遍历。

ac代码:

/**
 * 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>> v;
    void bfs(TreeNode *root)
    {
        int len=1,i,j,k;
        TreeNode *temp;
        queue q;
        q.push(root);
        while(!q.empty())
        {
            vector<int> num;
            k=0;
            for(i=0;ival);
                if(temp->left!=NULL)
                {
                    k++;
                    q.push(temp->left);
                }
                if(temp->right!=NULL)
                {
                    k++;
                    q.push(temp->right);
                }
            }
            len=k;
            v.push_back(num);
        }
    }
    vector<vector<int>> levelOrder(TreeNode *root) {
        // write your code here
        if(!root)
            return v;
        bfs(root);
        return v;
    }
};

你可能感兴趣的:(二叉树)