100. Same Tree

Posted bush2582

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了100. Same Tree相关的知识,希望对你有一定的参考价值。

100. Same Tree

1 题目

  1. 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

2 解题 && 思路

对2棵树分别做前序遍历,然后把前序的字符串比较。注意左右子树是空,需要特殊标记。

3. 实现

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def dlr(self,tree,dirlist):
        if tree is None :
            return 
        if tree.left is not None :
            self.dlr(tree.left,dirlist)
        else:
            dirlist.append(-2)
        dirlist.append(tree.val)
        if tree.right is not None :
            self.dlr(tree.right,dirlist)
        else:
            dirlist.append(-1)
        
    
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        p_list = []
        q_list = []

        self.dlr(p,p_list)
        self.dlr(q,q_list)
        p_str=""
        q_str=""
        for e in p_list:
            p_str = p_str+str(e)
        for e in q_list:
            q_str = q_str+str(e)
 
        return p_str == q_str
        

以上是关于100. Same Tree的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-- 100. Same Tree

[leetcode] 100 Same Tree

Leetcode-100 Same Tree

100. Same Tree

100. Same Tree(Tree)

小程序 - leetcode 100. Same Tree