LeetCode 10. Same Tree

xiaoxiao2021-02-28  151

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

二、输入输出

三、解题思路

递归遍历

很简单的一道题,只需要递归遍历树即可。退出条件写详细一点,分为如下几种情况:

两棵树全为nullptr

两棵树中一个为nullptr 一个不为空

两棵树中都不为空

当两棵树都不为空的时候,那么当前树相等,就等价于左子树和右子树全都相等,而且当前根节点的val也相同

/** * 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==nullptr && q == nullptr)return true; else if((p!=nullptr && q==nullptr) || (p==nullptr && q!=nullptr))return false; else if(p->val == q->val){ return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }else{ return false; } } };
转载请注明原文地址: https://www.6miu.com/read-24165.html

最新回复(0)