码迷,mamicode.com
首页 > 其他好文 > 详细

Same Tree

时间:2016-05-18 17:30:34      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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,有值,则有一个为空。

 

 

 

Same Tree

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5505688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!