zoukankan      html  css  js  c++  java
  • leetcode|Maximum 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.

    题目:意思很明确,求二叉树的深度

    思路:一看到二叉树,几乎本能的想到的是递归,于是按照这个思路搞了一版,没想到Accept的时候,报Time Exceeded Limit,效率不行。。。。于是优化之如下:

    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    * int val;
    * TreeNode left;
    * TreeNode right;
    * TreeNode(int x) { val = x; }
    * }
    */
    public class Solution {
      public int maxDepth(TreeNode root) {
        if (root == null) {//递归出口
        return 0;
      }
      int left = maxDepth(root.left);//左边多深
      int right = maxDepth(root.right);//右边呢
      if (left > right) {//比较一番,左边深
        return 1+left;
       } else {//好像还是右边深
        return 1+right;
       }
      }
    }

  • 相关阅读:
    一本通 P1806 计算器
    英语单词
    Dubbo springboot注解
    java连接zookeeper集群
    zookeeper集群
    入住博客园!
    解决 windows MySQL安装过程中提示计算机丢失vcruntime140_1.dll
    django 订单并发修改库存乐观悲观锁
    毒鸡汤
    Java反射机制
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5670145.html
Copyright © 2011-2022 走看看