# 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 p == None or q == None: if p == None and q == None: return True else: return False elif p.val == q.val: ans_l = self.isSameTree(p.left, q.left) ans_r = self.isSameTree(p.right, q.right) if ans_l == True and ans_r == True: return True else: return False else: return False
Java 版:
一起遍历两颗树
1. 当都为 null ,则返回 true ;
2. 其中一个为 null ,另一个不为 null,返回 false ;
3. 都不为null, 但节点的值不相等,也返回 false;
4. 否则,继续遍历左右子树。
class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) return true; if(p == null || q == null) return false; if(p.val != q.val) return false; boolean leftRes = isSameTree(p.left, q.left); boolean rightRes = isSameTree(p.right, q.right); return leftRes && rightRes; } }