简单
相关标签
相关企业
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:
输入: root = [1,null,2,3]
输出: [3,2,1]
解释:
示例 2:
输入: root = [1,2,3,4,5,null,8,null,null,6,7,9]
输出: [4,6,7,5,2,9,8,3,1]
解释:
示例 3:
输入: root = []
输出: []
示例 4:
输入: root = [1]
输出: [1]
提示:
- 树中节点的数目在范围
[0, 100]内 -100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
题解:
void postorder(struct TreeNode* root, int* returnSize, int* ans)
{
if (root == NULL)
{
return;
}
if (root->left != NULL)
{
postorder(root->left, returnSize, ans);
}
if (root->right != NULL)
{
postorder(root->right, returnSize, ans);
}
ans[*returnSize] = root->val;
(*returnSize) ++;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize = 0;
int* ans = (int*)malloc(sizeof(int) * 100);
postorder(root, returnSize, ans);
return ans;
}
第一次bug: Line 207: Char 3: runtime error: load of null pointer of type 'int' [Serializer.c] 报错原因是访问空指针(null pointer) 修改方法为:无论如何都是返回NULL,在递归遍历里面写if(root == NULL) return; 后续遍历的逻辑有问题:*returnSize = 0这句赋初值不应该放在递归函数里面,会被递归调用的。 修改后通过。