두 갈래 나무의 깊이가 두루 다니다

class Node(object):
    def __init__(self,x):
        self.val=x
        self.left=None
        self.right=None
class Solutuon(object):
    def max_deep(self,root):
        if not root:
            return 0
        else:
            l=self.max_deep(root.left)
            r=self.max_deep(root.right)
            l+=1
            r+=1
            return max(l,r)
class Tree(object):
    def __init__(self):
        self.root =None
    def add(self,item):
        node=Node(item)
        if self.root is None:
            self.root =node
            return
        queue=[self.root]
        while queue:
            cur_node=queue.pop(0)
            if cur_node.left is None:
                cur_node.left=node
                return
            else:
                queue.append(cur_node.left)
            if cur_node.right is None:
                cur_node.right =node
                return 
            else:
                queue.append(cur_node.right)
                
if __name__ =="__main__":
    tree=Tree()
    tree.add(0)
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    result=Solutuon()
    print(result.max_deep(tree.root))

좋은 웹페이지 즐겨찾기