题目:
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.
链接: http://leetcode.com/problems/same-tree/
一刷
class Solution(object): def isSameTree(self, p, q): if not p and not q: return True if not p or not q: return False return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
2/16/2017, Java, 冒险刷
1 public class Solution { 2 public boolean isSameTree(TreeNode p, TreeNode q) { 3 if (p == null && q == null) return true; 4 if (p == null && q != null || p != null && q == null) return false; 5 6 if (p.val != q.val) return false; 7 if (!isSameTree(p.left, q.left)) return false; 8 if (!isSameTree(p.right, q.right)) return false; 9 return true; 10 } 11 }