zoukankan      html  css  js  c++  java
  • maximun-depth-of-binary-tree

    题目:

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    此题类似二叉树最小深度。

    /**

     * Definition for binary tree

     * public class TreeNode {

     *     int val;

     *     TreeNode left;

     *     TreeNode right;

     *     TreeNode(int x) { val = x; }

     * }

     */

    import java.util.*;

    public class Solution {

        public int maxDepth(TreeNode root) {

            if(root==null)

                return 0;

            if(root.left==null&&root.right==null)

                return 1;

    方法一:递归

        /*    if(root.left==null)

                return maxDepth(root.right)+1;

            if(root.right==null)

                return maxDepth(root.left)+1;

            int left=maxDepth(root.left);

            int right=maxDepth(root.right);

           

            return (left>right)?(left+1):(right+1);

           

            */

            //方法二:层序遍历结束,每一层level加一

            Queue<TreeNode> q=new LinkedList<>();

            q.add(root);

            int level=0;

            while(!q.isEmpty()){

                int size=q.size();

                level++;

                for(int i=0;i<size;i++){

                    TreeNode node=q.poll();

                    if(node.left!=null)

                        q.add(node.left);

                    if(node.right!=null)

                        q.add(node.right);

                }

            }

           

            return level;

        }

    }

  • 相关阅读:
    mybatis 入门基础
    spring学习总结
    综合练习:词频统计
    组合数据类型综合练习
    Python基础综合练习
    熟悉常用的Linux操作
    1.大数据概述
    C程序语法(无左递归)
    文法规则
    实验一词法分析报告
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8029858.html
Copyright © 2011-2022 走看看