zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    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.

    解题思路:

    递归求得左子树的深度left_depth,右子树的深度right_depth,则 ans = max(left_depth, right_depth) + 1;

    代码:

     1 /**
     2  * Definition for binary tree
     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){
    14             return 0;
    15         }
    16         int left_depth = maxDepth(root->left);
    17         int right_depth = maxDepth(root->right);
    18         return max(left_depth, right_depth) + 1;
    19         
    20     }
    21     inline int max(int a, int b) {
    22         return a > b ? a : b;
    23     }
    24 };
  • 相关阅读:
    strncat_s
    资源编译器 (.rc) 文件
    C++ Namespace 详解
    Structure Definitions
    SetParent
    C++笔记(1)explicit构造函数
    .def
    tellg()和tellp()
    Data Groups
    Messages
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728251.html
Copyright © 2011-2022 走看看