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.

  思路:

    1、我用的是广搜,分别将其保存在两个列表里面,然后依次判断左右节点情况是否相同,并且判断其节点值是否相同,如果其中一个不相同就返回False,否则程序最后返回True. 缺点:代码复杂,不简洁

    2、有个大神用的递归,其实我也想过递归,但是没有做出来。

  代码:

    我的:

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p and q and p.val == q.val:
            a = [p]
            b = [q]
        elif not p and not q : return True
        else: return False
        while len(a) > 0:
            if a[0].left:
                if not b[0].left: return False
                else: 
                    if a[0].left.val != b[0].left.val: return False
                a.append(a[0].left)
                b.append(b[0].left)
            else: 
                if b[0].left: return False 
            if a[0].right:
                if not b[0].right: return False
                else: 
                    if a[0].right.val != b[0].right.val: return False
                a.append(a[0].right)
                b.append(b[0].right)
            else: 
                if b[0].right: return False
            a.pop(0)
            b.pop(0)
        return True

    大神的:

1 public boolean isSameTree(TreeNode p, TreeNode q) {
2     if(p == null && q == null) return true;
3     if(p == null || q == null) return false;
4     if(p.val == q.val)
5         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
6     return false;
7 }

    

posted @ 2017-09-07 14:57  唐僧洗发爱飘柔  阅读(150)  评论(0)    收藏  举报