LintCode 469 [Identical Binary Tree]

原题

检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。

样例

    1             1
   / \           / \
  2   2   and   2   2
 /             /
4             4

就是两棵等价的二叉树。

    1             1
   / \           / \
  2   3   and   2   3
 /               \
4                 4

就不是等价的。

解题思路

  • 如果两棵树都是None,认为是等价的
  • Recursion - 递归求解,分治的思路,如果a.val == b.val,则只需考虑左右子树是不是Identical Binary Tree

完整代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        this.val = val
        this.left, this.right = None, None
"""
class Solution:
    """
    @param a, b, the root of binary trees.
    @return true if they are identical, or false.
    """
    def isIdentical(self, a, b):
        # Write your code here
        if a is None and b is None:
            return True
        if a and b and a.val == b.val:
            return self.isIdentical(a.left, b.left) and self.isIdentical(a.right, b.right)
        return False
            

你可能感兴趣的:(LintCode 469 [Identical Binary Tree])