本文共 1553 字,大约阅读时间需要 5 分钟。
力扣练习题
给定一个二叉树,返回它的后序遍历。
示例图:(此处已去除图片链接)
二叉树的后序遍历(Postorder Traversal)是按照访问左子树、右子树、然后根节点的顺序遍历树的方式进行的。递归和迭代是实现后序遍历的两种主要方法,区别在于递归是隐式地使用栈,而迭代则需要显式地模拟栈。
这里提供了两种实现后序遍历的方法:递归和迭代。
#define SIZE 2000void postorder(struct TreeNode* root, int* res, int* resSize) { if (root == NULL) return; postorder(root->left, res, resSize); postorder(root->right, res, resSize); res[(*resSize)++] = root->val;}int* postorderTraversal(struct TreeNode* root, int* returnSize) { int* res = malloc(sizeof(int) * SIZE); *returnSize = 0; postorder(root, res, returnSize); return res;}
说明:
递归方法直接且简洁。每次递归先处理左子树,再处理右子树,最后将当前节点的值添加到结果数组中。需要注意的是,递归深度可能会导致栈溢出问题,特别是在处理非常大的树时。#define SIZE 2000int* postorderTraversal(struct TreeNode* root, int* returnSize) { int* res = malloc(sizeof(int) * SIZE); *returnSize = 0; struct TreeNode** stk = malloc(sizeof(struct TreeNode*) * SIZE); int top = 0; struct TreeNode* prev = NULL; while (root != NULL || top > 0) { while (root != NULL) { stk[top++] = root; root = root->left; } root = stk[--top]; if (root->right == NULL || root->right == prev) { res[(*returnSize)++] = root->val; prev = root; root = NULL; } else { stk[top++] = root; root = root->right; } } return res;}
说明:
迭代方法通过栈模拟递归过程。栈中记录需要处理的节点。每次从栈顶取出节点,如果其右子树为空或已被处理过,则将节点值添加到结果数组中;否则,将右子树节点加入栈并处理。这种方法避免了递归的潜在栈溢出问题,适合处理较大树结构。转载地址:http://zygfk.baihongyu.com/