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.
简单的递归。扩展版题目:leetcode 572
C++版:
/** * 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){ return false; } if(p->val==q->val){ return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); } return false; } };
python版:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if (not p) and (not q): return True elif (not p) or (not q): return False else: if p.val==q.val: return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) else: return False