leedcode_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.

Subscribe to see which companies asked this question.

題目簡單,遞歸的一個調用遍歷一遍樹就好了。qp同時遍歷,不同就返回。

代碼:

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


發佈了39 篇原創文章 · 獲贊 0 · 訪問量 4871
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章