二叉樹的層次遍歷
給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。
例如:
給定二叉樹: [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;
}