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;
       }
      }
    }

  • 相关阅读:
    京东分页
    相册分类列表页
    在线运行Javascript,Jquery,HTML,CSS代码
    点击事件后动画提示
    一些广告代码
    爱可有—之最经典
    爱可有网络社区需要定义
    鼠标移动时缩小图片显示说明
    Flask-RESTful 快速入门
    Sequelize 关系模型简介
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5670145.html
Copyright © 2011-2022 走看看