104. Maximum Depth of Binary Tree
求高度:后序遍历(从下往上计数)
求深度:前序遍历
根结点的高度就是二叉树的最大深度
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.getDepth(root)
def getDepth(self, node):
if node==None:
return 0
leftHeight = self.getDepth(node.left) #左
rightHeight = self.getDepth(node.right) #右
height = 1+ max(leftHeight,rightHeight) #中
return height
111. Minimum Depth of Binary Tree
最小深度:根结点到最近叶子的距离
左右中
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.getMinDepth(root)
def getMinDepth(self,node):
if node == None:
return 0
leftHeight = self.getMinDepth(node.left)
rightHeight = self.getMinDepth(node.right)
if node.left is None and node.right is not None:
return 1+rightHeight
if node.right is None and node.left is not None:
return 1+leftHeight
result = 1+min(leftHeight,rightHeight)
return result
222. Count Complete Tree Nodes
可以层序递归/前中后
此代码为后序遍历,没有用完全二叉树的特性
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.getNum(root)
def getNum(self,node):
if node == None:
return 0
#后序遍历
leftNum = self.getNum(node.left)
rightNum = self.getNum(node.right)
result = leftNum + rightNum +1
return result
用完全二叉树的特性可以少遍历几个节点
写递归时有两个终止条件,1.reach null; 2.左右两边深度相等
如果这个节点两侧深度一样,number of nodes=2^depth -1
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
left =root.left
right = root.right
leftDepth = 0
rightDepth = 0
while left:
left = left.left
leftDepth +=1
while right:
right = right.right
rightDepth +=1
if leftDepth == rightDepth:
return (2<<leftDepth)-1
return self.countNodes(root.left)+self.countNodes(root.right)+1