LeetCode Easy: 100. Same Tree

一、题目

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

比较两棵二叉树,看其是否相等。

二、思路

可以采用递归方式,分三种情况:

1、两棵树均为空,返回True;

2、两棵树一空一非空,返回False;

3、两棵树的值相等,然后递归判断其子结点是否相等;

三、代码

#coding:utf-8
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        # if p == None and q == None:
        #     print('True')
        #     return True
        # elif p == None or q== None:
        #     print('False')
        #     return False
        # elif p.val == q.val:
        #     print(self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right))
        #     return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
        # else:
        #     print("False")
        #     return False

#采用栈的方式,非递归 stack = [(p, q)] while stack: p, q = stack.pop() if p == None and q == None: continue if p == None or q == None: print('False') return False if p.val == q.val: stack.append((p.right, q.right)) stack.append((p.left, q.left)) else: print('False') return False print('True') return True if __name__ == '__main__': S = Solution() l1 = TreeNode(4) l2 = TreeNode(2) l3 = TreeNode(6) l4 = TreeNode(1) l5 = TreeNode(4) l6 = TreeNode(2) l7 = TreeNode(6) root1 = l1 l1.left = l2 l1.right = l3 root2 = l2 l2.left = l4 l2.right = l5 root3 = l1 l3.left = l6 l3.right = l7 #S.isSameTree(root1,root2) S.isSameTree(root1,root3)

  还有一种采用非递归的方式,来源于博客:https://blog.csdn.net/lilong_dream/article/details/22753227

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8708748.html