Lintcode: 二叉树的层次遍历

问题:

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

样例:

样例 1:

输入:{1,2,3}
输出:[[1],[2,3]]
解释:
   1
  / \
 2   3
它将被序列化为{1,2,3}
层次遍历

样例 2:

输入:{1,#,2,3}
输出:[[1],[2],[3]]
解释:
1
 \
  2
 /
3
它将被序列化为{1,#,2,3}
层次遍历

python:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Level order a list of lists of integer
    """
    def levelOrder(self, root):
        # write your code here
        result = []
        if root == None:
            return result
        q = []
        q.append(root)
        while len(q) != 0:
            res = []
            for i in range(len(q)):
                node = q.pop(0)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
                res.append(node.val)
            result.append(res)
        return result

 

 

C++:

 

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: Level order a list of lists of integer
     */
    vector> levelOrder(TreeNode * root) {
        // write your code here
        vector> result;
        if(!root)
        {
            return result;
        }
        queue q;
        q.push(root);
        
        while(!q.empty())
        {
            vector res;
            int len = q.size();
            while(len--)
            {
                TreeNode *temp = q.front();
                res.push_back(temp->val);
                if(temp->left)
                {
                    q.push(temp->left);
                }
                if(temp->right)
                {
                    q.push(temp->right);
                }
                q.pop();
            }
            result.push_back(res);
        }
   
        return result;  
    }
};

 

PS:设置循环到最小单元即可解决。

 

你可能感兴趣的:(Lintcode)