LeetCode993(2021.5.17)

LC993. 二叉树的堂兄弟节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {
public:
    int x, y;
    TreeNode* x_parent, * y_parent;
    int x_depth, y_depth;
    bool x_found = false, y_found = false;

    void dfs(TreeNode* node, int depth, TreeNode* parent) {
        if (!node) return;
        if (node->val == x) tie(x_parent, x_depth, x_found) = tuple{parent, depth, true};
        else if (node->val == y) tie(y_parent, y_depth, y_found) = tuple{parent, depth, true};

        if (x_found && y_found) return;
        dfs(node->left, depth + 1, node);
        if (x_found && y_found) return;
        dfs(node->right, depth + 1, node);
    }

    bool isCousins(TreeNode* root, int x, int y) {
        this->x = x;
        this->y = y;
        dfs(root, 0, nullptr);
        return x_depth == y_depth && x_parent != y_parent;
    }
};

发表评论