代码随想录算法训练营第16天 | 104.二叉树的最大深度 、111.二叉树的最小深度、222.完全二叉树的节点个数

93 阅读2分钟

 104.二叉树的最大深度 (优先掌握递归)

思路:之前层次遍历法做过很简单,现在尝试一下递归来做

  1. 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
int getdepth(TreeNode node)
  1. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
if (node == NULL) return 0;
  1. 确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
int leftdepth = getdepth(node.left);       // 左
int rightdepth = getdepth(node.right);     // 右
int depth = 1 + Math.max(leftdepth, rightdepth); // 中
return depth;

完整代码:

class Solution {
    /**
     * 递归法
     */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

题目链接/文章讲解/视频讲解: programmercarl.com/0104.%E4%BA…

 111.二叉树的最小深度 

和最大深度 看似差不多,其实 差距还挺大,有坑。

class Solution {
    /**
     * 递归法,相比求MaxDepth要复杂点
     * 因为最小深度是从根节点到最近**叶子节点**的最短路径上的节点数量
     */
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null) {
            return rightDepth + 1;
        }
        if (root.right == null) {
            return leftDepth + 1;
        }
        // 左右结点都不为null
        return Math.min(leftDepth, rightDepth) + 1;
    }
}

题目链接/文章讲解/视频讲解:programmercarl.com/0111.%E4%BA…

 222.完全二叉树的节点个数(优先掌握递归)

class Solution {
    // 通用递归解法
    public int countNodes(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftNum = countNodes(root.left);      // 左
        int rightNum = countNodes(root.right);    // 右
        int treeNum = leftNum + rightNum + 1;      // 中
        return treeNum;
    }
}

题目链接/文章讲解/视频讲解:programmercarl.com/0222.%E5%AE…

总结

感觉递归还是不好理解,还是得再好好看看,脑子现在昏昏的