leetcode100. Same Tree

easy程度題

Q:

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.

判斷兩個二叉樹是否相同

思路:
類似於二叉樹的前序遍歷,將兩個二叉樹按照相同的順序交替壓棧,然後出棧比較棧頂的兩個元素(兩個二叉樹位於相同位置的節點)是否相同

AC解:

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) 
    {//類似先序遍歷
        stack<TreeNode*> s;
        s.push(q);
        s.push(p);

        while (!s.empty())
        {
            p = s.top();    s.pop();
            q = s.top();    s.pop();

            if (p == nullptr && q == nullptr)    continue;
            if (p == nullptr || q == nullptr)    return false;
            if (p->val != q->val)                return false;

            s.push(q->right);
            s.push(p->right);
            s.push(q->left);
            s.push(p->left);
        }

        return true;
    }
};

遞歸解法:

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q)
    {
        if (p == nullptr && q == nullptr) return true; //終止條件
        if (p == nullptr || q == nullptr) return false;  //剪枝
        return p->val == q->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right);  //三方合併
    }
}
發佈了66 篇原創文章 · 獲贊 21 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章