[LeetCode] 100. Same Tree

题:https://leetcode.com/problems/same-tree/description/

题目

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

思路

利用广度遍历,对比每个节点。

note:以前说用两种 树的遍历就可以 确定一棵树,但当书中两个节点的值一样的时候,这个方法不适用。

code

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

def isSameTree(p,q):
    if p == None and q == None:
        return True
    if p == None or q ==None:
        return False
    if p.val == q.val:
        return isSameTree(p.left,q.left) and isSameTree(p.right,q.right)
    return False

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        return isSameTree(p,q)

对比 前序遍历 和 中序遍历

# Definition for a binary tree node.
# 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
        """
        preorder = []
        inorder = []
        tstack = [] 

        while p != None or len(tstack)!=0:
            while p !=None:
                preorder.append(p.val)
                tstack.append(p)
                p = p.left
            p = tstack.pop(-1)
            inorder.append(p.val)
            p = p.right
        ipre = 0
        iin = 0
        tstack = []

        while q!=None or len(tstack)!=0:
            while q!=None:
                print(q.val)
                if ipre>=len(preorder) or q.val != preorder[ipre]:
                    return False
                ipre += 1
                tstack.append(q)
                q = q.left
            q = tstack.pop(-1)
            if iin>=len(inorder) or q.val != inorder[iin]:
                return False

            iin+=1
            q = q.right
        if len(preorder) == ipre:
            return True
        return False

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/80929265