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

【LeetCode每天一题】Same Tree(相同的树)

时间:2019-05-11 21:42:17      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:turn   microsoft   解决   init   family   节点   fun   none   class   

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.

Example 1:

Input:     1          1
             / \        /             2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
             /                       2              2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1          1
             / \        /            2   1     1   2

        [1,2,1],   [1,1,2]

Output: false 

思路

  这道题很简单我们使用前序遍历的方法一个一个的进行比较,然后判断是否相等,如果中途任意一个不相等或者一个节点为空都直接返回false。
解题代码

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def isSameTree(self, p, q):
10         """
11         :type p: TreeNode
12         :type q: TreeNode
13         :rtype: bool
14         """
15         if not p and not q:
16             return True
17         if not p or not q:
18             return False 
19         if p.val == q.val:  
20             return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 
21         return False
  一开始写的解决代码,但是发现可以写的更简单一点
 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def isSameTree(self, p, q):
10         """
11         :type p: TreeNode
12         :type q: TreeNode
13         :rtype: bool
14         """
15         if not p and not q:
16             return True
17         return self.preorder(p, q)
18         
19         
20     def preorder(self, p, q):
21         if not p and not q:  # 都为空返回True
22             return True
23         if not p or not q:        # 如果其中一个为空返回False
24             return False
25         if p.val == q.val:        # 值相等的话直接继续判断
26             res = self.preorder(p.left, q.left) and self.preorder(p.right, q.right)
27             return res
28         return False 

【LeetCode每天一题】Same Tree(相同的树)

标签:turn   microsoft   解决   init   family   节点   fun   none   class   

原文地址:https://www.cnblogs.com/GoodRnne/p/10849987.html

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