zoukankan      html  css  js  c++  java
  • 【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;
    }
  • 相关阅读:
    逆元(费马小定理求法)
    CodeForces
    lower_bound and upper_bound
    HDU 4825 Xor Sum
    1030: [JSOI2007]文本生成器
    1070: [SCOI2007]修车
    agc 027 B
    P2664 树上游戏
    CF 314 E. Sereja and Squares
    4237: 稻草人
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14180487.html
Copyright © 2011-2022 走看看