104.二叉树的最大深度
二叉树的最大深度
首先go中求max的函数在math包中,输入输出均为float64.
一般而言,前序遍历时求解深度问题,后续遍历是求解高度问题,但是代码随想录将这个问题定义为高度问题,所以转换为求高度,采用了后续遍历。
func maxDepth(root *TreeNode) int {
return GetDepth(root)
}
func GetDepth(root *TreeNode) int{
if root == nil {return 0}
left := GetDepth((*root).Left)
right := GetDepth((*root).Right)
return int(math.Max(float64(left),float64(right))) + 1
}
559.n叉树的最大深度
n叉树的最大深度
这道题和二叉树最大深度是一样的,只不过将遍历左右节点换成了遍历所有的节点
func maxDepth(root *Node) int {
return GetNMax(root)
}
func GetNMax(root *Node) int{
if root == nil{
return 0
}
max := 0
for i := 0; i < len((*root).Children); i++{
tmp := GetNMax((*root).Children[i])
if tmp > max{
max = tmp
}
}
return max + 1
}
222.完全二叉树的节点个数
完全二叉树的节点个数
首先如果是迭代法可以直接层序遍历最后一行, 然后加上前几行即可,因为前几行一定是满二叉树。
如果要用迭代的话,可以参考下面的方法,判断左右节点拥有几层满二叉树,然后根据 2^n - 1求出满二叉树的节点,然后左+ 右 + 1即可求出总数。
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便
while (left) { // 求左子树深度
left = left->left;
leftDepth++;
}
while (right) { // 求右子树深度
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};