p30 对二叉树进行层次遍历 (leetcode 102)

一:解题思路

二:完整代码示例 (C++版和Java版)

C++:

class Solution 
{
public:
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
        vector<vector<int>> result;
        queue<TreeNode*> q;

        if (root != NULL)
            q.push(root);

        while (!q.empty())
        {
            int size = q.size();
            vector<int> elem;

            for (int i = 0; i < size; i++)
            {
                TreeNode* node = q.front();
                q.pop();

                elem.push_back(node->val);

                if (node->left != NULL) q.push(node->left);
                if (node->right != NULL) q.push(node->right);
            }

            result.push_back(elem);
        }

        return result;
    }
};

Java:

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root)
    {
        List<List<Integer>> result=new ArrayList<>();
        Queue<TreeNode> q=new LinkedList<>();

        if(root!=null)
            q.add(root);

        while(!q.isEmpty())
        {
            int size=q.size();
            List<Integer> elem=new ArrayList<>();

            for(int i=0;i<size;i++)
            {
                TreeNode node=q.poll();
                elem.add(node.val);
                
                if(node.left!=null) q.add(node.left);
                if(node.right!=null) q.add(node.right);
            }
            
            result.add(elem);
        }

        return result;
    }
}

 

上一篇:数组的合并 总结的几种方法


下一篇:#102 二叉树的层次遍历