Leetcode在线编程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.
题意
判断题目给定的2个二叉树是否相等
解题思路
先判断是否2个可能不能同时为空或者同时为非空(异或大法)
接着若有一个为空,则肯定两个都是空了
最后就是递归判断左右子树是否都是相等
AC代码
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(!p ^ !q)
return false;
if(!p)
return true;
if(p->val == q->val)
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
else
return false;
}
};
本文针对LeetCode上的二叉树相等问题进行详细解析,介绍了如何通过递归方式判断两棵二叉树是否完全相同,包括结构一致且节点值相等的情况。通过具体的AC代码实现展示了这一过程。
126

被折叠的 条评论
为什么被折叠?



