第六週Same Tree

Same Tree

Leetcode algorithms problem 100:Same Tree

  • 問題描述

    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.

  • 問題提示

  • 思路

    使用遞歸,首先返回節點爲NULL時的相等情況;兩個節點都是有效指針時,如果根值不一樣,返回false,一樣則進入遞歸:根的左側樹是相同的(遞歸)&&根的右側樹是相同的(遞歸),否則返回false

代碼

/**
 * 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 isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL||q==NULL) {
            return (p == q);
        }else {
            if(p->val != q->val){
                return false;
            }else{
                return (isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
            }
        }
    }
};

時間複雜度: O(n)
空間複雜度: O(2^n)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章