首页 > 其他分享 >代码随想录 第十六天 | ● 104.二叉树的最大深度 559.n叉树的最大深度 ● 111.二叉树的最小深度 ● 222.完全二叉树的节点个数

代码随想录 第十六天 | ● 104.二叉树的最大深度 559.n叉树的最大深度 ● 111.二叉树的最小深度 ● 222.完全二叉树的节点个数

时间:2024-03-09 14:11:06浏览次数:15  
标签:return int 随想录 二叉树 深度 null root 节点

leetcode:104. 二叉树的最大深度 - 力扣(LeetCode)

思路:递归判断每次左右节点的是否存在,存在自然加一,return的1就是这样,判断子节点的左右两端是否有节点,统计有的节点数量,也就是左右的高度

class Solution {
    public int maxDepth(TreeNode root) {
        //后序遍历
        if( root == null) return 0;
        int leftheight = maxDepth(root.left);
        int rightheight = maxDepth(root.right);
        return 1+Math.max(leftheight,rightheight);
    }

}

 

leetcode:111. 二叉树的最小深度 - 力扣(LeetCode)

思路:后序遍历,唯一不同点在最小子节点不能把null算上,分类讨论左右节点分别为null的情况

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int leftheight = minDepth(root.left);
        int rightheight = minDepth(root.right);
        //和最大深度不同的是,节点为空时,不能算作子节点,所以要分类讨论左右节点为空的情况
        if(root.left == null && root.right != null) return 1+rightheight;
        if(root.left != null && root.right == null) return 1+leftheight;
        return 1 + Math.min(leftheight,rightheight);
    }
}

leetcode:559. N 叉树的最大深度 - 力扣(LeetCode)

思路:和二叉树左右节点思路一致,唯一区别在多个子节点,使用数组判断每个节点的子节点的深度,两两比较最大值

class Solution {
    public int maxDepth(Node root) {
        if(root == null) return  0;
        int n = 0;
        //判断上一个和现在children的深度
        for(Node child : root.children){
            n = Math.max(n,maxDepth(child));
        }
        return n + 1;
    }

}

leetcode:222. 完全二叉树的节点个数 - 力扣(LeetCode)

思路:判断左右子节点的数目是否相同,相同利用公式快速记录满叉树节点数目,剩下的正常记录,递归真好用,

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null)return 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        int leftlen = 0;
        int rightlen = 0;
     //记录两边左右节点数目 while(left != null){ left = left.left; leftlen++; } while(right != null){ right = right.right; rightlen++; } //成立说明是满叉树,直接带入公式 if(leftlen == rightlen) return (2 <<leftlen ) - 1; int leftsum = countNodes(root.left); int rightsum = countNodes(root.right); return 1 + leftsum + rightsum; } }

 

标签:return,int,随想录,二叉树,深度,null,root,节点
From: https://www.cnblogs.com/lengbo/p/18062345

相关文章