码迷,mamicode.com
首页 > 其他好文 > 详细

两道关于binary tree的水题 [Same Tree] [Maximum Depth of Binary Tree]

时间:2014-11-15 11:13:11      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   sp   for   div   

 

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

 

 

两道关于binary tree的水题 [Same Tree] [Maximum Depth of Binary Tree]

标签:des   style   blog   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/kevin-/p/4098987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!