leetcode 49: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.

示例1

输入

{1},{1}

输出

true
示例2

输入

{1,2},{1,#,2}

输出

false
题目分析:
只要两个树中对应的两个节点的值不同,或者一个节点为空,另一个节点存在则都可认为两颗树是不相同的。代码如下:
 1  bool isSameTree(TreeNode* p, TreeNode* q) {
 2         if(p == NULL&& q == NULL)
 3             return true;
 4         if(p == NULL || q == NULL)
 5             return false;
 6         if(p->val != q->val)
 7             return false;
 8         
 9          return isSameTree(p->left, q->left)&&isSameTree(p->right, q->right);
10     }
原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/13450855.html