學渣帶你刷Leetcode145. 二叉樹的後序遍歷

題目描述

白話題目:
 

算法:

 

詳細解釋關注 B站  【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB

C語言完全代碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
#define MAX_SIZE 512

void postorder(struct TreeNode* root, int* result, int* returnSize) {
  if (root) {
    postorder(root->left, result, returnSize);
    postorder(root->right, result, returnSize);
    result[(*returnSize)++] = root->val;
  }
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
  int* result = (int*)malloc(MAX_SIZE * sizeof(int));
  *returnSize = 0;
  postorder(root, result, returnSize);
  return result;
}
/*迭代
#define MAX_SIZE 512

int* postorderTraversal(struct TreeNode* root, int* returnSize) {
  *returnSize = 0;
  int* result = (int*)malloc(MAX_SIZE * sizeof(int));
  struct TreeNode** stack = (struct TreeNode**)malloc(MAX_SIZE * sizeof(struct TreeNode*));
  struct TreeNode *p = root, *r;
  int top = -1;
  while (p || top != -1) {
    if (p) {
      stack[++top] = p;
      p = p->left;
    } else {
      p = stack[top];
      if (p->right && p->right != r) {
        p = p->right;
        stack[++top] = p;
        p = p->left;
      } else {
        p = stack[top--];
        result[(*returnSize)++] = p->val;
        r = p;
        p = NULL;
      }
    }
  }
  return result;
}
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章