zoukankan      html  css  js  c++  java
  • [LeetCode系列] 二叉树最大深度求解问题(C++递归解法)

    问: 给定二叉树, 如何计算二叉树最大深度?

    算法描述如下:

    1. 如果当前节点为空, 返回0(代表此节点下方最大节点数为0)
    2. 如果当前节点不为空, 返回(其左子树和右子树下方最大节点数中的最大值+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)
    14             return 0;
    15         return max(maxDepth(root->left), maxDepth(root->right))+1;
    16     }
    17 private:
    18     int max(int a, int b) {
    19         return a>b?a:b;
    20     }
    21 };
  • 相关阅读:
    P1909 买铅笔
    树形结构
    图片
    cookie
    JSON
    操作数组
    竖线分割|
    订单提交中... 后前面三点动画
    w'w
    解决扫码枪输入input时受中文输入法的影响
  • 原文地址:https://www.cnblogs.com/lancelod/p/3848692.html
Copyright © 2011-2022 走看看