平衡二叉树:任何一个节点的左右子树高度差绝对值不超过一。
求高度,使用后序遍历,当发现任何一个节点的左右子树高度差超过一时,直接返回-1给上一个节点,告诉此树已经不是平衡二叉树了!当遍历完成,还没return -1 ,那说明就是平衡二叉树了。
class Solution:
def getheight(self,node):
if node == None:
return 0
leftHeight = self.getheight(node.left)
if leftHeight == -1:
return -1
rightHeight = self.getheight(node.right)
if rightHeight == -1:
return -1
if abs(leftHeight - rightHeight) > 1:
return -1
else:
return 1 + max(leftHeight , rightHeight)
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if root == None:
return True
if self.getheight(root) != -1:
return True
else:
return False
中序遍历的逻辑,但是把加入当前节点值的这一步放到了前面
class Solution:
def travel(self,node, path , res):
path.append(node.val)
if not node.left and not node.right:
sPath = '->'.join(map(str, path))
res.append(sPath)
return
if node.left:
self.travel(node.left , path , res)
path.pop()
if node.right:
self.travel(node.right , path , res)
path.pop()
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
path , res = [] , []
if not root:
return res
self.travel(root , path , res)
return res
本题的递归出口并不是在左叶子节点处,而是在左叶子节点的父亲节点处,这样才能访问到叶子节点
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left and not root.right:
return 0
leftSum = self.sumOfLeftLeaves(root.left)
#找到了左叶子节点
if root.left and not root.left.left and not root.left.right:
leftSum = root.left.val
rightSum = self.sumOfLeftLeaves(root.right) # 右
sum_val = leftSum + rightSum # 中
return sum_val
先用层序秒一遍,增加下信心~
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
res , queue = [] , collections.deque([root])
if not root:
return 0
while queue:
for _ in range(len(queue)):
node = queue.popleft()
res.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return len(res)
后续遍历也熟悉一遍:
class Solution:
def func(self , node):
if not node:
return 0
leftSum = self.func(node.left)
rightSum = self.func(node.right)
sum = leftSum + rightSum + 1
return sum
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return self.func(root)
可以注意到,递归遍历的时间复杂度比层序更低