100. Same Tree

来源:互联网 发布:英文翻译什么软件好 编辑:程序博客网 时间:2024/06/07 08:55

题目原文

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.


思路

  1. 为空判断
  2. 若当前节点值相等且利用递归判断左子树与右子树均相等,则返回true,否则返回false

代码

class Solution {public:    bool isSameTree(TreeNode* p, TreeNode* q) {        if(!p&&!q) return true;        else if(p&&!q) return false;        else if(!p&&q) return false;        else{            if((p->val)==(q->val)&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)) return true;            return false;        }    }};
0 0