LeetCode 104. 二叉树的最大深度
题目链接:104. 二叉树的最大深度
思路:首先明确定义,什么是二叉树的深度,什么是二叉树的高度。
引用代码随想录
二叉树节点的深度:从根节点到该节点的最长简单路径边的条数(从1开始计数)或者节点数(从0开始计数);
二叉树节点的高度:从该节点到叶子节点的最长简单路径边的条数(从1开始计数)或者节点数(从0开始计数)。
所以,二叉树的最大深度就是从根节点到(最远端的)叶子节点的条数或者节点数,即根节点的高度。
使用递归的方法,类似二叉树后序遍历的方法,不断寻找最“深”的叶子节点。
Python版本:
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def getDepth(root):
if not root:
return 0
leftDepth = getDepth(root.left)
rightDepth = getDepth(root.right)
res = max(leftDepth, rightDepth)+1
return res
return getDepth(root)
时间复杂度: O ( n ) O(n) O(n),空间复杂度: O ( h e i g h t ) O(height) O(height)
go版本:
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
LeetCode 111. 二叉树的最小深度
题目链接:111. 二叉树的最小深度
思路:根据上一题的定义分析得出,二叉树的最小深度是根节点到离它最近的叶子节点的条数或者节点数。这个题和上一题的区别是求最大深度还是最小深度的问题,最大深度比较好理解,那最小深度是什么意思呢?我们重新回去阅读一下定义,根节点到离它最近的叶子节点的条数或者节点数,根节点非常好确定,而叶子节点的定义就是本题解题的关键。
叶子节点是左右孩子都为空的节点,所以这也是我们单层递归的逻辑判断条件!
Python版本:
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def getDepth(root):
if not root:
return 0
leftDepth = getDepth(root.left)
rightDepth = getDepth(root.right)
if root.left and not root.right:
return leftDepth+1
if not root.left and root.right:
return rightDepth+1
return min(leftDepth, rightDepth)+1
return getDepth(root)
时间复杂度: O ( n ) O(n) O(n),空间复杂度: O ( h e i g h t ) O(height) O(height)
go版本:
func minDepth(root *TreeNode) int {
if root == nil {
return 0;
}
if root.Left == nil && root.Right != nil {
return 1 + minDepth(root.Right);
}
if root.Right == nil && root.Left != nil {
return 1 + minDepth(root.Left);
}
return min(minDepth(root.Left), minDepth(root.Right)) + 1;
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
Google大佬们什么时候能给go多写点api啊
LeetCode 222. 完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数
思路:老规矩,先理解透定义。
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1 − 2 h 1-2^h 1−2h 个节点。
通俗一点讲,就是除了最底层可以缺点(叶子)节点外,其余位置节点必须一个不缺;且最底层的叶子节点们也都要尽量靠左。挖坑:完全二叉树的实际工程意义有什么?
所以递归的逻辑就是先求当前节点的左子树的节点数量,再求它的右子树的节点数量,最后取总和加一 (因为还要算上当前节点)。
Python版本:
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
def foo(root):
if not root:
return 0
return foo(root.left)+foo(root.right)+1
return foo(root)
时间复杂度: O ( n ) O(n) O(n),空间复杂度: O ( h e i g h t ) O(height) O(height)
go版本:
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
return countNodes(root.Left)+countNodes(root.Right)+1
}