本文主要是介绍C语言 | Leetcode C语言题解之第145题二叉树的后序遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
void addPath(int *vec, int *vecSize, struct TreeNode *node) {int count = 0;while (node != NULL) {++count;vec[(*vecSize)++] = node->val;node = node->right;}for (int i = (*vecSize) - count, j = (*vecSize) - 1; i < j; ++i, --j) {int t = vec[i];vec[i] = vec[j];vec[j] = t;}
}int *postorderTraversal(struct TreeNode *root, int *returnSize) {int *res = malloc(sizeof(int) * 2001);*returnSize = 0;if (root == NULL) {return res;}struct TreeNode *p1 = root, *p2 = NULL;while (p1 != NULL) {p2 = p1->left;if (p2 != NULL) {while (p2->right != NULL && p2->right != p1) {p2 = p2->right;}if (p2->right == NULL) {p2->right = p1;p1 = p1->left;continue;} else {p2->right = NULL;addPath(res, returnSize, p1->left);}}p1 = p1->right;}addPath(res, returnSize, root);return res;
}
这篇关于C语言 | Leetcode C语言题解之第145题二叉树的后序遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!