zoukankan      html  css  js  c++  java
  • 牛客题霸NC13二叉树的最大深度Java题解

    牛客题霸NC13二叉树的最大深度Java题解

    https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73?tpId=117&&tqId=34934&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

    方法1:层序遍历
    解题思路:利用队列进行层序遍历,每遍历完一层深度加1

    import java.util.*;
     
    /*
     * public class TreeNode {
     *   int val = 0;
     *   TreeNode left = null;
     *   TreeNode right = null;
     * }
     */
     
    public class Solution {
        /**
         *
         * @param root TreeNode类
         * @return int整型
         */
        public int maxDepth (TreeNode root) {
            if(root == null){
                return 0;
            }
            LinkedList<TreeNode> queue  = new LinkedList<>();  //利用队列遍历二叉树的每个节点
            LinkedList<TreeNode> tmp;     
            queue.addFirst(root);
            int res=0;
            while(!queue.isEmpty()){
     
                tmp = new LinkedList<>();           //tmp暂存下一层的节点
                for(int i = queue.size();i>0;i--){  //遍历当前层的节点
     
                   TreeNode node = queue.removeLast();       
     
                   if(node.left!=null){            //如果左子节点不为null,将左子节点加入到队列中
                    tmp.addFirst(node.left);
                   }
                   if(node.right!=null){           //如果右子节点不为null,将右子节点加入到队列中
                    tmp.addFirst(node.right);
                   }
                }
                queue = tmp;                     //将下一层的节点放入队列中
                res++;                           //每遍历完一层,res加1
            }
             return res;
        }
    }

    方法2:递归
    解题思路:递归遍历左右子树,最大深度等于左右子树中较大的加1

    import java.util.*;
     
    /*
     * public class TreeNode {
     *   int val = 0;
     *   TreeNode left = null;
     *   TreeNode right = null;
     * }
     */
     
    public class Solution {
        /**
         *
         * @param root TreeNode类
         * @return int整型
         */
        public int maxDepth (TreeNode root) {
            if(root == null) {
                return 0;
            }
            return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        }
    }
  • 相关阅读:
    文字
    <script type="text/x-template"> 模板
    防xss攻击
    url
    symmfony
    composer
    header 和http状态码
    bootstrap
    linux的设置ip连接crt,修改主机名,映射,建文件
    Centos上传下载小工具lrzsz
  • 原文地址:https://www.cnblogs.com/yunfeiyang2020/p/14045116.html
Copyright © 2011-2022 走看看