代码随想录算法训练营DAY16 | 二叉树 (3)

一、LeetCode 104 二叉树的最大深度

题目链接:104.二叉树的最大深度icon-default.png?t=N7T8https://leetcode.cn/problems/maximum-depth-of-binary-tree/

思路:采用后序遍历递归求解。

class Solution {
    int ans = 0;
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        int depth = 1 + Math.max(left,right);
        return depth;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

二、LeetCode 111 二叉树的最小深度

题目链接:111.二叉树的最小深度icon-default.png?t=N7T8https://leetcode.cn/problems/minimum-depth-of-binary-tree/

思路:左右孩子均为空才是叶子节点,才可以计算深度。

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 1 + right;
        }
        //右子树为空,左子树不空的情况
        if(root.left != null && root.right == null){
            return 1 + left;
        }
        return 1 + Math.min(left,right);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

三、LeetCode 222 完全二叉树的节点个数

题目链接:222.完全二叉树的节点个数icon-default.png?t=N7T8https://leetcode.cn/problems/count-complete-tree-nodes/description/

思路:分别计算左右子树节点个数,再相加。

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        //分别计算左右子树节点个数 再相加
        int left = countNodes(root.left);
        int right = countNodes(root.right);
        return left + right + 1;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

四、今日小结

        偷得浮生半日闲~

你可能感兴趣的:(代码随想录算法训练营,算法)