Python - DFS: level traversal and check if each level are palindrome


  • 0
    A

    Python - DFS: level traversal and check if each level are palindrome

    class Solution:
    # @param {TreeNode} root
    # @return {boolean}
    def isSymmetric(self, root):
        tra = [] # traversal
        self.dfs(root, 0, tra)
        if len(tra) <= 1:
            return True
        
        for i in range(1, len(tra)):
            for j in range( len(tra[i])/2 ):
                if tra[i][j] != tra[i][-j-1]:
                    return False
        
        return True
    
    def dfs(self, root, level, tra):
        if len(tra) < level + 1:
            tra.append([])
            
        if not root:
            tra[level].append(None)
            return
        
        tra[level].append(root.val)
        self.dfs(root.left, level+1, tra)
        self.dfs(root.right, level+1, tra)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.