代码随想录Day16 | 104. 二叉树的最大深度、111. 二叉树的最小深度、222. 完全二叉树的节点个数 | 二叉树、递归

132 阅读2分钟

104. 二叉树的最大深度

题目链接:104. 二叉树的最大深度

思路: 题目问的是最大深度,可以理解为根节点的高度。这题使用后序遍历,因为父节点只有知道子节点的高度,才能计算自己的高度。

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        return Math.max(left, right) + 1;
    }
}

总结:

分清楚高度和深度的概念,深度:  节点到根结点路径上的节点数(从上往下计数),相关问题用前序遍历高度:  节点到叶子节点路径上的节点数(从下往上计数),高度相关问题用后序遍历

111. 二叉树的最小深度

题目链接:111. 二叉树的最小深度

思路: 以为把最大深度的max改为min就可以了,没有考虑到子树为空的情况。当左子树/右子树为空时,应该返回右子树/左子树的高度 + 1。否则才返回左子树和右子树的较小值 + 1。

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = minDepth(root.left);
        int right = minDepth(root.right);

        if (root.left == null && root.right != null) return right + 1;
        if (root.right == null && root.left != null) return left + 1;
        return Math.min(left, right) + 1;
    }
}

总结:

222. 完全二叉树的节点个数

题目链接:222. 完全二叉树的节点个数

思路:

第一想法直接遍历每个节点来做了,没有利用到完全二叉树的特性。完全二叉树意味着左右子树至少有一个是满二叉树,满二叉树的节点个数可以用2 ^ 树的高度 - 1获得。

我的代码:

class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        TreeNode l = root, r = root;
        int hl = 0, hr = 0;
        while (l != null) {
            l = l.left;
            hl++;
        }
        while (r != null) {
            r = r.right;
            hr++;
        }
        if (hl == hr) {
            return (int)Math.pow(2, hl) - 1;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}

总结:

复习二叉树的递归操作。