/*
* 算法思想:
* 使用两个栈,一个son stack一个root stack,其中son子节点,root用来存放父节点,
* 迭代过程为:
* 1. 每次从son stack中取出一个节点node, 压栈到root stack中去;
* 2. 然后判断该节点node是否有左孩子,有的话压栈到son stack;
* 3. 判断该节点node是否有右孩子,有的话,压栈到son stack;
* 4. 当son stack中有元素的话,一直将上述1-3过程循环下去,循环结束后,root stack中的元素即为结果;
* 5. 依次pop root stack中的元素,顺序即为后序遍历的结果。
*/
#define LEN 100
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
struct TreeNode *node;
struct TreeNode **root_stack;
struct TreeNode **son_stack;
int *arr;
int root_index = 0;
int son_index = 0;
int arr_index = 0;
if(!root) {
*returnSize = 0;
return NULL;
}
root_stack = (struct TreeNode **)malloc(LEN * sizeof(struct TreeNode *));
son_stack = (struct TreeNode **)malloc(LEN * sizeof(struct TreeNode *));
arr = (int *)malloc(LEN * sizeof(int));
if(!root)
return NULL;
node = root;
son_stack[son_index++] = node;
while(son_index){
node = son_stack[--son_index];
root_stack[root_index++] = node;
if(node->left)
son_stack[son_index++] = node->left;
if(node->right)
son_stack[son_index++] = node->right;
}
while(root_index){
node = root_stack[--root_index];
arr[arr_index++] = node->val;
}
free(son_stack);
free(root_stack);
*returnSize = arr_index;
return arr;
}
leetcode-145. 二叉树的后序遍历-C语言
最新推荐文章于 2020-06-15 19:51:59 发布