104 Maximum Depth of Binary Tree

这题我还考过别人,试图用一句code完成,然后结合minDepth放在一起考别人。。下一题写minDepth

之前的代码,好大一段,我确实是个认真boy。。。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 
import java.util.List;
import java.util.ArrayList;

public class Solution {
    public int maxDepth(TreeNode root) {
        // 仍然可以用两种方法实现;1,遍历,while()内部,当list isEmpty()的时候return
        // 2, 递归还是那么好写,只要改一下函数名和 Math.max就好了。。。
        
        // solution 1
        
/*        if(root==null) return 0;
        
        List<TreeNode> list = new ArrayList<TreeNode>();
        list.add(root);
        int depth=0;  // 判断初值!!
        while(true){
            List<TreeNode> current = new ArrayList<TreeNode>();
            for(TreeNode node: list){
                if(node.left!=null) current.add(node.left);
                if(node.right!=null) current.add(node.right);
            }
            depth++;
            list = current;
            if(list.isEmpty()) return depth;  // 当上一层是最底层的时候,这一层是空的,所以这里把 判断最底层的问题 转化为isEmpty()来表示
            
        }  // !!!注意了,当有while(true) 的时候,循环体里面包含了return,那么可以不用在while之外包含return,compiler会识别出 unreachable statement.  // 耗时3ms,才5%*/
        
/*        // solution 2
        if(root==null) return 0;
        if(root.left==null && root.right==null) return 1;
        if(root.left==null) return 1+ maxDepth(root.right);
        if(root.right==null) return 1+ maxDepth(root.left);
        if(root.left!=null && root.right!=null) return 1+ Math.max(maxDepth(root.left), maxDepth(root.right));
        return -1;*/
        
        // solution 3, a more concise version of solution2, but the algo is the same;
        
        if(root==null) return 0;
        else return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        
    }
}


今天的代码:

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        return 1+Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值