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

Posted goodrnne

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode每天一题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.

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(相同的树)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode每天一题Binary Tree Zigzag Level Order Traversal(二叉树的之字形遍历)

LeetCode每天一题Construct Binary Tree from Preorder and Inorder Traversal(使用前序和中序遍历构建二叉树)

100.Same Tree

LeetCode 100. Same Tree

LeetCode 100. Same Tree (相同的树)

0100-Same Tree(相同的树)