zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    求二叉树深度,直接看代码:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxDepth(TreeNode* root) {
    13         if(root == NULL) return 0;
    14         _max = 1;
    15         tranverse(root->left, 1);
    16         tranverse(root->right, 1);
    17         return _max;
    18     }
    19     void tranverse(TreeNode * node, int count)
    20     {
    21         if(node == NULL)
    22             return;
    23         else{ 
    24             if(count + 1 > _max)
    25                 _max = count + 1;
    26             tranverse(node->left, count + 1);
    27             tranverse(node->right, count + 1);
    28         }
    29     }
    30 public:
    31     int _max;
    32 };

     java版的如下所示,上面的递归写的还是太麻烦了,下面的简单很多哈:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int maxDepth(TreeNode root) {
    12         if(root == null)
    13             return 0;
    14         return tranverse(root, 0);
    15     }
    16     
    17     public int tranverse(TreeNode root, int val){
    18         if(root.left == null && root.right == null)
    19             return val+1;
    20         int leftDep = 0, rightDep = 0;
    21         if(root.left != null)
    22             leftDep = tranverse(root.left, val + 1);
    23         if(root.right != null)
    24             rightDep = tranverse(root.right, val + 1);
    25        return Math.max(leftDep, rightDep);
    26     }
    27 }
  • 相关阅读:
    T-SQL:Varchar和Nvarchar区别(八)
    UI5-文档-4.1-Hello World!
    UI5-文档-4-Walkthrough
    UI5-文档-3-Hello World!
    UI5-文档-2.5-开发混合Web容器
    UI5-文档-2.4-Node.js-Based开发环境
    UI5-文档-2.3-使用SAPUI5工具为Eclipse开发应用程序
    UI5-文档-2.2-使用SAP Web IDE开发应用程序
    UI5-文档-2.1-使用OpenUI5开发应用
    UI5-文档-2-开发环境
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4904924.html
Copyright © 2011-2022 走看看