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;

        }

    }

  • 相关阅读:
    I
    D
    K
    G
    J
    Doom HDU
    Mountaineers Gym
    华南理工大学“三七互娱杯”程序设计竞赛(重现赛)( HRY and array 高精度除法模板)
    Corn Fields POJ
    linux如何安装缺失依赖
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8029858.html
Copyright © 2011-2022 走看看