104. Maximum Depth of Binary Tree
Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路:其实就是左右中的后序遍历。具体见昨天的练习。
# 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):
return self.getdepth(root)
def getdepth(self, node):
if not node:
return 0
leftheight = self.maxDepth(node.left)
rightheight = self.maxDepth(node.right)
height = 1 + max(leftheight, rightheight)
return height
222. Count Complete Tree Nodes
类似上一题,但是这题是计算node个树。
class Solution:
def countNodes(self, root: TreeNode) -> int:
return self.getNodesNum(root)
def getNodesNum(self, cur):
if not cur:
return 0
leftNum = self.getNodesNum(cur.left) #left
rightNum = self.getNodesNum(cur.right) #right
treeNum = leftNum + rightNum + 1 #middle
return treeNum
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
只有当一个节点的左右节点都为空时,才是最低点。画出一个这样的二叉树就知道了。
class Solution:
def getDepth(self, node):
if node is None:
return 0
leftDepth = self.getDepth(node.left)
rightDepth = self.getDepth(node.right)
# only when both left and right are empty, it is the lowest point
if node.left is None and node.right is not None:
return 1 + rightDepth
if node.left is not None and node.right is None:
return 1 + leftDepth
result = 1 + min(leftDepth, rightDepth)
return result
def minDepth(self, root):
return self.getDepth(root)