872. Leaf-Similar Trees(有空研究下栈算法)

题目

如果两棵树得到的叶子序列相同,那么是一组叶子相似树。
在这里插入图片描述

我的代码

# 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 leafSimilar(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: bool
        """
        temp=[]
        def traverse(T):
            nonlocal temp
            if T:
                if not T.left and not T.right:
                    temp.append(T.val)
                else:
                    traverse(T.left)
                    traverse(T.right)
        traverse(root1)
        result1=temp 
        temp=[]
        traverse(root2)   
        return result1==temp

高效的栈算法

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

class Solution:
    def leafSimilar(self, root1: 'TreeNode', root2: 'TreeNode') -> 'bool':
        result1 = [ ]
        stack1 = [ ]
        result2 = [ ]
        stack2 = [ ]
        if root1:
            stack1.append(root1)
        while stack1:
            cur = stack1.pop()
            if cur.left is None and cur.right is None:
                result1.append(cur.val)
            if cur.right:
                stack1.append(cur.right)
            if cur.left:
                stack1.append(cur.left)
       
        if root2:
            stack2.append(root2)
        while stack2:
            cur = stack2.pop()
            if cur.left is None and cur.right is None:
                result2.append(cur.val)
            if cur.right:
                stack2.append(cur.right)
            if cur.left:
                stack2.append(cur.left)
        
        return "".join(map(str, result1)) == "".join(map(str, result2)) 

猜你喜欢

转载自blog.csdn.net/xiabenshu/article/details/88827198
今日推荐