题目
给定一个 N
叉树,返回其节点值的后序遍历。
递归法很简单,你可以使用迭代法完成此题吗?
函数原型
C
的函数原型:
/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* postorder(struct Node* root, int* returnSize) {
}
算法设计:递归
思路:N叉树后序遍历:叶子节点 -> 根节点。
void rescurion(struct Node* root, int *size, int *arr){
if(root)
for(int i=0; i<root->numChildren; i++){
rescurion(root->children[i], size, arr);
arr[(*size)++] = root->children[i]->val;
}
}
int* postorder(struct Node* root, int* returnSize) {
int *arr = malloc(sizeof(int) * 10240);
*returnSize = 0;
if(root == NULL)
return arr;
rescurion(root, returnSize, arr);
arr[(*returnSize)++] = root->val;
return arr;
}
- 时间复杂度: Θ ( N ) \Theta(N) Θ(N)
- 空间复杂度:
Θ
(
N
)
\Theta(N)
Θ(N)
算法设计:迭代
思路:先将根压入栈,然后pop出栈,并对其子节点进行遍历并压入栈,循环直到栈为空,最后将list反转。
/**
* 迭代
**/
#define MAX_SIZE 10240
void reverse(int* array, int arraySize) {
for (int i = 0, j = arraySize - 1; i <= j; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int* postorder(struct Node* root, int* returnSize) {
int top = -1, *result = (int*)calloc(MAX_SIZE, sizeof(int));
struct Node* p = NULL;
struct Node** stack = (char**)malloc(sizeof(struct Node*) * MAX_SIZE);
*returnSize = 0;
if (root == NULL) return result;
stack[++top] = root;
while (top != -1) {
p = stack[top--];
if (p) result[(*returnSize)++] = p->val;
for (int i = 0; i < p->numChildren; i++) {
stack[++top] = p->children[i];
}
}
reverse(result, *returnSize); // 反转
free(stack);
return result;
}
- 时间复杂度: Θ ( N ) \Theta(N) Θ(N)
- 空间复杂度: Θ ( N ) \Theta(N) Θ(N)