Leetcode 100.same tree

原題地址:https://leetcode.com/problems/same-tree/description/

題目描述

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.

判斷兩棵樹是否相同。

思路

這一題的思路和上一題(題號(hào)617)挺像的。設(shè)了個(gè)bool變量areSame來表示是否相同,初始為true。同步遍歷兩棵樹,通過比較當(dāng)前節(jié)點(diǎn)的值和左右子節(jié)點(diǎn)的情況來決定接下來的操作。

代碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool areSame = true;
    
    void travelTogether(TreeNode* p,TreeNode* q){
        if(p->val != q->val){
            areSame = false;
            return ;
        }
        if(p->left !=NULL && q->left!=NULL){
            travelTogether(p->left,q->left);
        }else if(p->left ==NULL && q->left==NULL){
            //should not return directly here
        }else{
            areSame = false;
            return  ;
        }
        if(p->right!=NULL && q->right!=NULL){
            travelTogether(p->right,q->right);
        }else if(p->right==NULL && q->right==NULL){

        }else{
            areSame = false;
            return ;
        }
        
    }
    
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL && q==NULL){
            return true;
        }
        if(p==NULL || q==NULL){
            return false;
        }
        travelTogether(p,q);
        return areSame;
    }
};

踩坑

遇到一個(gè)小問題。在travelTogether函數(shù)里判斷左子節(jié)點(diǎn)的分支的情況的時(shí)候(22行處),如果進(jìn)入到兩棵樹的當(dāng)前父節(jié)點(diǎn)都沒有左子節(jié)點(diǎn)的情況時(shí),原本在那個(gè)分支里寫了個(gè)return語句直接返回了,但是這樣就導(dǎo)致不會(huì)執(zhí)行接下來對右子節(jié)點(diǎn)的操作。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容