100. 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.
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p != nullptr && q != nullptr) { return (p->val == q->val) && isSameTree(p->right,q->right) && isSameTree(p->left,q->left); } else if (p == nullptr && q == nullptr) { return true; } else if (p == nullptr || q == nullptr) { return false; } return false; } };
1 class Solution { 2 public boolean isSameTree(TreeNode p, TreeNode q) { 3 //base case 4 if(p==null || q==null) return p==null&& q==null; 5 //recursion 6 return p.val==q.val && isSameTree(p.left,q.left) && isSameTree(q.right,p.right); 7 } 8 }