• 【leetcode】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;
    }
    int *postorderTraversal(struct TreeNode *root, int *returnSize) {
        int *res = malloc(sizeof(int) * 2001);
        *returnSize = 0;
        if (root == NULL) {
            return res;
        }
        struct TreeNode **stk = malloc(sizeof(struct TreeNode *) * 2001);
        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;
    }
  • 相关阅读:
    poj2502(最短路)
    poj1511(最小环和)
    uva11090(spfa判负环)
    hdu4370(spfa最短路最小环)
    uva10561(SG)
    uvalive5059(SG)
    uvaliva3905(扫描线)
    scu4445(模拟)
    uvalive3902(树上的最优化 贪心)
    scu4444(完全图最短路)
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14180487.html
Copyright © 2020-2023  润新知