leetcodeブラシ問題.まとめる

926 ワード

leetcode 100問題は2つのツリーが同じかどうかを判断することです
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
この問題は同様に深さ優先探索を用い,再帰を用いて,まず現在のノード値が同じか否かを判断し,次に各現在のノードの左右のサブツリーが同じか否かを判断し,3つの条件が同じであれば真に戻る.再帰終了条件は,2本の木が最も遠い葉ノードを遍歴し,真を返すか,あるいはそのうちの1つが最も遠い葉ノードに着いたが,もう1つはなかったので,偽を返すことである.
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if (p == NULL && q == NULL)
    return true;
    else if (p == NULL || q == NULL)
    return false;
    
    bool flagV;
    if (p->val == q->val)
    flagV = true;
    else
    flagV = false;
    
    bool flagL = isSameTree(p->left, q->left);
    bool flagR = isSameTree(p->right, q->right);
    
    if (flagL && flagR && flagV)
    return true;
    else
    return false;
}