程式語言 - LeetCode - C - 1372. Longest ZigZag Path in a Binary Tree



參考資訊:
https://www.cnblogs.com/cnoodle/p/17342376.html

題目:


解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int max(int a, int b)
{
    return a > b ? a : b;
}

int travel(struct TreeNode *n, int cnt, int *m, int left)
{
    if (left) {
        if (n->left) {
            travel(n->left, cnt + 1, m, 0);
        }

        if (n->right) {
            travel(n->right, 1, m, 1);
        }
    }
    else {
        if (n->right) {
            travel(n->right, cnt + 1, m, 1);
        }

        if (n->left) {
            travel(n->left, 1, m, 0);
        }
    }

    *m = max(cnt, *m);
    return 0;
}

int longestZigZag(struct TreeNode *root)
{
    int r = 0;

    travel(root, 0, &r, 0);

    return r;
}