题目:
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 class Solution 2 { 3 public: 4 bool isSameTree(TreeNode *p, TreeNode *q) 5 { 6 if (!p && !q) return true; // 终止条件 7 if (!p || !q) return false; 8 return p->val == q->val // 三方合并 9 && isSameTree(p->left, q->left) 10 && isSameTree(p->right, q->right); 11 } 12 };
这题开始写错了,主要是没考虑第二种情况
第一种,节点都为nullptr,两树相等,主要用于叶子节点的判断
第二种,一个节点存在val,一个节点为nullptr,这样的话在语法上用p->val == q ->val 是错的,因为节点为nullptr的没有val
第三种,val存在且相等,分别判断两个树的左右子树是否相等