python基礎程式設計——樹的高度
阿新 • • 發佈:2018-12-12
樹的高度
題目描述
現在有一棵合法的二叉樹,樹的節點都是用數字表示,現在給定這棵樹上所有的父子關係,求這棵樹的高度
輸入描述:
輸入的第一行表示節點的個數n(1 ≤ n ≤ 1000,節點的編號為0到n-1)組成,
下面是n-1行,每行有兩個整數,第一個數表示父節點的編號,第二個數表示子節點的編號
輸出描述:
輸出樹的高度,為一個整數
示例:
輸入:
5
0 1
0 2
1 3
1 4
輸出:
3
mycode:
通過率為50%
cnt = int(input())
Btree = [0] * (cnt + 1)
for i in range(0, cnt-1):
x, y = map(int, input ().split(" "))
Btree[y] = x
height = 1
for j in range(cnt-1, 0, -1):
index = j
count = 1
while index:
index = Btree[index]
count += 1
if count > height:
height = count
print(height)
other’s code:
通過率為100%
n = input()
tree = [1] * n
childnum = [0] * n
for i in range(0, n-1):
parent, this = map(int, input().split(" "))
if childnum[parent] >= 2:
tree[this] = 0
childnum[this] = 2
continue
tree[this] += tree[parent]
childnum[parent] += 1
print (max(tree))
小結:
測試樣例中有多叉樹的情況,估計出題人的意圖就是讓我們將資料刪減為二叉樹。
補充:
本題中沒有用到標準的樹的insert來構建一個數。下面簡單介紹:
樹的列表表示:
def BinaryTree(r):
return [r, [], []]
myTree = ['a', #root
['b', #left subtree
['d', [], []],
['e', [], []] ],
['c', #right subtree
['f', [], []], [] ] ]
def insertLeft(root,newBranch):
t = root.pop(1)
if len(t) > 1:
root.insert(1,[newBranch,t,[]])
else:
root.insert(1,[newBranch, [], []])
return root
def insertRight(root,newBranch):
t = root.pop(2)
if len(t) > 1:
root.insert(2,[newBranch,[],t])
else:
root.insert(2,[newBranch,[],[]])
return root
def getRootVal(root):
return root[0]
def setRootVal(root,newVal):
root[0] = newVal
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
樹的節點表示:
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key
r = BinaryTree('a')
print(r.getRootVal())
print(r.getLeftChild())
r.insertLeft('b')
print(r.getLeftChild())
print(r.getLeftChild().getRootVal())
r.insertRight('c')
print(r.getRightChild())
print(r.getRightChild().getRootVal())
r.getRightChild().setRootVal('hello')
print(r.getRightChild().getRootVal())