LEETCODE —— binary tree [Same Tree] && [Maximum Depth of Binary Tree]

时间:2021-06-30 23:06:16

Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

SAME TREE
'''
SAME TREE
Created on Nov 13, 2014

@author: ScottGu<gu.kai.66@gmail.com, 150316990@qq.com>
'''
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param p, a tree node
    # @param q, a tree node
    # @return a boolean
    def isSameTree(self, p, q):
        self.__init__()
        self.foreachNode(p)
        seqP=self.seq

        self.__init__()
        self.foreachNode(q)
        seqQ=self.seq

        return seqP==seqQ

    def __init__(self):
        self.seq=[]

    def foreachNode(self, node):
        if(node==None): return
        self.seq.append(node.val)
        self.foreachNode(node.left)
        self.foreachNode(node.right)
MAX DEPTH
'''
MAX DEPTH
Created on Nov 13, 2014

@author: ScottGu<gu.kai.66@gmail.com, 150316990@qq.com>
'''
class Solution:
    # @param root, a tree node
    # @return an integer
    def maxDepth(self, root):
        self.__init__()
        self.foreachNode(root)
        return self.max

    def __init__(self):
        self.depth=0
        self.max=0

    def foreachNode(self, node):
        if(node==None): return 

        self.depth+=1
        if(node.left==None and node.right==None):
            if(self.depth>self.max):
                self.max=self.depth
        self.foreachNode(node.left)
        self.foreachNode(node.right)
        self.depth-=1

if __name__ == '__main__':
    pass