I've recently solved the LeetCode's Same Tree problem: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.The problem itself and the idea is simple: traverse the tree in a way that preserves the structure - returning None for non-existing left or right sub-tree.Here is the complete working code:from itertools import izipdef traverse(node):    if not node:        yield None    else:        yield node.val        if node.left:            for val in traverse(node.left):                yield val        else:            yield None        if node.right:            for val in traverse(node.right):                yield val        else:            yield Noneclass Solution(object):    def isSameTree(self, p, q):                :type p: TreeNode        :type q: TreeNode        :rtype: bool                try:            for node_p, node_q in izip(traverse(p), traverse(q)):                if node_p != node_q:                    return False        except StopIteration:            return True        return TrueIt was accepted by the Online Judge, but the code looks a bit lengthy. Is there a way to further simplify or improve the solution? Also, is it the most optimal way to solve the problem?Note that I cannot use yield from since the OJ is Python 2.7 only.FYI, here is what LeetCode uses as a Tree/Node:# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = None
Check if two binary trees are equal
python;python 2.7;tree
Since you have a check if not node, can't you just ignore checking if node.left and if node.right? How about:def traverse(node):    if not node:        yield None    else:        yield node.val        for val in traverse(node.left):            yield val        for val in traverse(node.right):            yield valAlso in line for node_p, node_q in izip(traverse(p), traverse(q)) you have misleading variable names, since node_p and node_q aren't actually nodes, but their values.Was class Solution a requirement? Because it isn't easy to use:s = Solution()result = s.isSameTree(root1, root2)It'd be easier to use a function instead:result = isSameTree(root1, root2)Or mayberesult = root1.isSameAs(root2)And if you want to keep the class then Solution isn't a great name either because you can apply different arguments to it. Checker or Comparator would indicate performed functionality more clearly.