Same Tree

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.

简单题,对两棵二叉树同时执行前序,中序或者后序遍历,如果每一时刻访问的结点的值都相同(或者同时为叶子结点)则可以认为两棵树相同。这里选择前序遍历,比较简单,有递归和迭代两种解法。
递归解法如下:
class Solution:
    """
    @param a, b, the root of binary trees.
    @return true if they are identical, or false.
    """
    def isIdentical(self, a, b):
        if not a and not b:
            return True 
        if not  a  or not b :
            return False
        if a.val != b.val:
            return False
        return self.isIdentical(a.left,b.left) and self.isIdentical(a.right,b.right)

迭代解法并不需要同时维护两个栈,只需要一次push或者pop两个结点就可以了,代码如下:

class Solution:
    """
    @param a, b, the root of binary trees.
    @return true if they are identical, or false.
    """
    def isIdentical(self, a, b):
        
        stack = [b,a]
        
        while stack:
            p1=stack.pop()
            p2=stack.pop()
            if not p1 and not p2:
                continue
            if not p1 or not p2:
                return False
            if p1.val != p2.val:
                return False
                
            stack.extend([p2.right,p1.right])
            stack.extend([p2.left,p1.left])
            
        return True

注意在 not a and not b 判断二者都不为空之后,判断两者是否有一个为空的好办法是:not a or not b,有值,则有一个为空。

 

 

 

posted on 2016-05-18 16:25  Sheryl Wang  阅读(164)  评论(0编辑  收藏  举报

导航