二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
返回其层次遍历结果:
C++,应该是最短的代码了。
层序遍历一般来说确实是用队列实现的,但是这里很明显用递归前序遍历就能实现呀,而且复杂度O(n)。。。
要点有几个:
利用depth变量记录当前在第几层(从0开始),进入下层时depth + 1;
如果depth >= vector.size()说明这一层还没来过,这是第一次来,所以得扩容咯;
因为是前序遍历,中-左-右,对于每一层来说,左边的肯定比右边先被遍历到,实际上后序中序都是一样的。。。
代码如下:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
pre(root, 0, ans);
return ans;
}
void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
if (!root) return ;
if (depth >= ans.size())
ans.push_back(vector<int> {});
ans[depth].push_back(root->val);
pre(root->left, depth + 1, ans);
pre(root->right, depth + 1, ans);
}
};
C语言也是构造二维数组进行存储:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int getdepth(struct TreeNode *root){
if(root == NULL) return 0;
int l = getdepth(root->left), r = getdepth(root->right);
return (l > r ? l : r) + 1;
}
void getcnt(struct TreeNode *root, int k, int *cnt){
if(root == NULL) return;
cnt[k] += 1;
getcnt(root->left, k + 1, cnt);
getcnt(root->right, k + 1, cnt);
return;
}
void getresult(struct TreeNode *root, int k,int *cnt, int **ret){
if(root == NULL) return;
ret[k][cnt[k]++] = root->val;
getresult(root->left, k + 1, cnt, ret);
getresult(root->right, k + 1, cnt, ret);
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
int depth = getdepth(root);
int **ret = (int **)malloc(sizeof(int *) * depth);
int *cnt = (int *)calloc(depth, sizeof(int));
getcnt(root, 0, cnt);
// cnt[0] = 1, cnt[1] = 2, cnt[3] = 2;
for(int i = 0; i < depth; i++){
ret[i] = (int *)malloc(sizeof(int) * cnt[i]);
cnt[i] = 0;
}
getresult(root, 0, cnt ,ret);
*returnSize = depth;
*returnColumnSizes = cnt;
return ret;
}