【LeetCode】102. Binary Tree Level Order Traversal

问题描述

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

问题分析

树的层次遍历。递归,在每一次迭代中传入当前的层次,将层次作为数组的索引,再将当前节点的值push到对应层次的数组里。

代码

class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int> > r;
        fun(root, r, 0);
        return r;
    }
    
    void fun(TreeNode* p, vector<vector<int> > &r, int level) {
    	if(p==0) return;
    	if(r.size()<=level) {
			r.push_back(vector<int>());
	    }
	    r[level].push_back(p->val);
	    fun(p->left, r, level+1);
	    fun(p->right, r, level+1);
    }
};