您的位置:首页 > 编程语言 > C语言/C++

LeetCode 100. Same Tree 题解(C++)

2016-10-12 11:35 417 查看

LeetCode 100. Same Tree 题解(C++)

题目描述

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.

思路

使用递归实现。首先先判断两个结点是否同时为空,是的话则返回true,若一个结点为空,另一个结点为非空,则返回false;

再判断两个结点的值是否相等,若不等则返回false;

之后分别对左右子树进行递归,分别判断左右子树是否一样(这里的一样指的是形状相识,对应结点值相等),并返回左右子树返回的bool值的逻辑与。

代码

/**
* 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;
}
if (p->val != q->val)
{
return false;
}
bool isSameLeftTree = isSameTree(p->left, q->left);
bool isSameRightTree = isSameTree(p->right, q->right);
return isSameLeftTree && isSameRightTree;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++