打印二叉树的边界节点
生活随笔
收集整理的這篇文章主要介紹了
打印二叉树的边界节点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一顆二叉樹的頭節點,按照如下兩種標準分別實現二叉樹邊界節點的逆時針打印
標準一:1、頭節點為邊界節點? 2、葉節點為邊界節點? 3、如果節點在其所在的層中的最左邊或最右邊,那么也是邊界節點
class Node:def __init__(self,value):self.value = valueself.left = Noneself.right = Nonedef getHeight(head,i):if head == None:return ireturn max(getHeight(head.left,i+1),getHeight(head.right,i+1))def printEdge(head):if head == None:returnheight = getHeight(head,0)edgeMap = [[None for i in range(2)] for j in range(len(height))]setedgeMap(head,0,edgeMap)//打印左邊界for i in range(len(edgeMap)):print(edgeMap[i][0].value + " ")//打印非左邊界、右邊界的葉子節點printInfo(head)//打印右邊界for i in range(len(edgeMap)-1,-1,-1):if edgeMap[i][0]!=edgeMap[i][1]:print(edgeMap[i][1].value + " ")def printInfo(head,i,edgeMap):if head == None:return if head.left == None and head.right == None and head!=edgeMap[i][0] and head!=edgeMap[i][1]:print(head.value + " ")printInfo(head.left,i+1,edgeMap)printInfo(head.right,i+1,edgeMap)def setedgeMap(head,i,edgeMap):if head == None:return if edgeMap[i][0] == None:edgeMap[i][0] = headedgeMap[i][1] = headsetedgeMap(head.left,i+1,edgeMap)setedgeMap(head.right,i+1,edgeMap)標準二:1、頭節點為邊界節點 2、葉節點為邊界節點? 3、樹左邊界延伸下去的路徑為邊界節點 4、數右邊界延伸下去的路徑為邊界節點
def printEdge2(head):if head == None:returnprint(head.value + " ")if head.left!=None and head.right!=None:printLeftEdge(head.left,true)printRightEdge(head.right,true)elif head.left != None:printEdge2(head.left)else:printEdge2(head.right)def printLeftEdge(head,isPrint): if head == None:returnif isPrint or (head.left == None and head.right == None):print(head.value + " ")printLeftEdge(head.left,isPrint)printLeftEdge(head.right,bool(isPrint and root.left==None))def printRightEdge(head,isPrint):if head == None:returnprintRightEdge(head.left,bool(isPrint and head.right == None))printRightEdge(head.right,isPrint)if isPrint or (head.left==None and head.right==None):print(head.value + " ")?
總結
以上是生活随笔為你收集整理的打印二叉树的边界节点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求最短通路值
- 下一篇: 根据后续数组重建搜索二叉树