【演算法 in python | 樹】其他試題
阿新 • • 發佈:2018-11-07
1. 對稱二叉樹
判斷一個樹是否是對稱的。(遞迴)
def sym(head): if head is None: return True else: return cmp(head.left, head.right) def cmp(left,right): if left is None and right is None: return True elif left is None or right is None: return False elif left.val != right.val: return False else: return cmp(left.left, right.right) and cmp(left.right, right.left)
2. 映象二叉樹(遞迴)
def mirrorTree(head): if head is None or (head.left is None and head.right is None): return else: temp = head.left head.left = head.right head.right = temp if head.left: mirrorTree(head.left) if head.right: mirrorTree(head.right)
3. 二叉樹深度(遞迴)
def depthTree(head):
if head is None:
return 0
else:
return 1+ max(depthTree(head.left), depthTree(head.right))
4. 二叉樹寬度(層次遍歷二叉樹,逐行列印二叉樹):
def widthTree(head): res = [] width = 0 if head is None: return 0 queue = [head] while len(queue) > 0: res.append([i.val for i in queue]) width = len(queue) for i in range(len(queue)): p = queue.pop(0) if p.left: queue.append(p.left) if p.right: queue.append(p.right) return width
5. 平衡二叉樹(遞迴)
一棵樹,若左右子樹高度差不超過1,則為平衡二叉樹
def balance(head):
if head is None:
return True
if abs(depthTree(head.left) - depthTree(head.right)) > 1:
return False
return balance(head.left) and balance(head.right)
6. 重建二叉樹(已知前序,中序)(遞迴)
def rebuild(pre,mid):
if len(pre) == 0:
return
if len(pre) == 1:
return TreeNode(pre[0])
index = mid.index(pre[0])
t = TreeNode(pre[0])
t.left = rebuild(pre[1:index + 1], mid[:index])
t.right = rebuild(pre[index+1:], mid[index+1:])
return t
7. 二叉搜尋樹(二叉排序樹)第k個節點
二叉搜尋樹:左子樹>跟>右子樹,與中序遍歷對應
class Solution:
# 返回對應節點TreeNode,中序遍歷即可
def __init__(self):
self.result = []
def KthNode(self, pRoot, k):
if k <= 0:
return None
else:
self.midsort(pRoot)
if k > len(self.result):
return None
return self.result[k-1]
def midsort(self, p):
if p == None:
return None
else:
self.midsort(p.left)
self.result.append(p)
self.midsort(p.right)
8. 二叉搜尋樹後序遍歷
判斷某序列是否為二叉搜尋樹後續遍歷的結果。
class Solution:
def VerifySquenceOfBST(self, sequence):
# 二叉搜尋樹後序序列,最後一個節點是根節點,剩下的可以分成兩個序列
#左邊的都比根小,右邊的都比根大
if sequence == []:
return False
return self.judge(sequence)
def judge(self,sequence):
if len(sequence) == 0:
return True
root = sequence.pop(-1)
left = [i for i in sequence if i < root]
right = [i for i in sequence if i > root]
if left +right == sequence:
return self.judge(left) and self.judge(right)
else:
return False