【leetcode】872.Leaf-Similar Trees

【leetcode】872.Leaf-Similar Trees_第1张图片
就是找到二叉树的所有叶子节点,很easy 的DFS
自己的写法

# 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, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: bool
        """
        self.array = []
        self.DFS(root1)
        res1 = []+self.array

        self.array=[]
        self.DFS(root2)
        res2 = [] +self.array
        return res1 ==res2

    def DFS(self,root):
        if root.left == None and root.right == None:
            self.array.append(root.val)
        else:
            if root.left!=None:
                self.DFS(root.left)
            if root.right!=None:
                self.DFS(root.right)

大佬的写法

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def leafSimilar(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: bool
        """
        return self.DFS(root1) == self.DFS(root2)
    def DFS(self,root):
        if root ==None: return []
        #叶子节点
        if root.left ==None and root.right==None:
            return [root.val]
        return self.DFS(root.left) + self.DFS(root.right)

遍历的时候,用来的存储遍历结果的数组可以不用放在最外层(我写的那样),可以让遍历函数自己返回(第二种方法),这样使得程序更具有鲁棒性。比如中序遍历可以写成如下简单的形式

    def DFS(self,root):
        if root ==None:return []
        return self.DFS(root.left) +[root.val] + self.DFS(root.right)

你可能感兴趣的:(LeetCode)