劍指offer系列(十四)二叉樹的深度,平衡二叉樹,陣列中只出現一次的數字
阿新 • • 發佈:2018-11-11
二叉樹的深度
題目描述
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。
解題思路:
利用遞迴實現。如果一棵樹只有一個結點,那麼它的深度為1。遞迴的時候無需判斷左右子樹是否存在,因為如果該節點
為葉節點,它的左右子樹不存在,那麼在下一級遞迴的時候,直接return 0。同時,記得每次遞迴返回值的時候,深度加一操
作,因為計算深度是從根節點下面一個節點開始計算的。
程式碼:
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def TreeDepth(self, pRoot): # write code here if pRoot == None: return 0 return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
平衡二叉樹
題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
解題思路:
如果二叉樹的每個節點的左子樹和右子樹的深度不大於1,它就是平衡二叉樹。
先寫一個求深度的函式,再對每一個節點判斷,看該節點的左子樹的深度和右子樹的深度的差是否大於1
程式碼:
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here if pRoot == None: return True depth1 = self.GetDepth(pRoot.left) depth2 = self.GetDepth(pRoot.right) if abs(depth1-depth2)>1: return False return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) def GetDepth(self, root): if not root: return 0 return max(self.GetDepth(root.left), self.GetDepth(root.right))+1
陣列中只出現一次的數字
題目描述
一個整型數組裡除了兩個數字之外,其他的數字都出現了偶數次。請寫程式找出這兩個只出現一次的數字。
解題思路:
用python自帶的Counter庫。返回一個列表,map(f,input),對input進行f操作,第一個引數lambda函式,意思取返回值中的第一個數,因為counter函式返回的是字典,counter().most_common返回的是有序的計數字段,取最後兩個,順序是從大到小的
list(map(lambda c:c[0],Counter(array).most_common()[-2:]))
程式碼:
# -*- coding:utf-8 -*- class Solution: # 返回[a,b] 其中ab是出現一次的兩個數字 def FindNumsAppearOnce(self, array): # write code here from collections import Counter return list(map(lambda c:c[0], Counter(array).most_common()[-2:]))