美文网首页
Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

作者: 一枚煎餅 | 来源:发表于2016-09-18 05:40 被阅读0次
Maximum Depth of Binary Tree.png

解題思路 :

從 root 開始做 recursive 回傳以左右兩邊 child 為起點的高度 取最大的一邊加上 1 (root本身) 如果 root 本身是 nullptr 就回傳 0

C++ code :

<pre><code>
/**

  • Definition of TreeNode:
  • class TreeNode {
  • public:
  • int val;
    
  • TreeNode *left, *right;
    
  • TreeNode(int val) {
    
  •     this->val = val;
    
  •     this->left = this->right = NULL;
    
  • }
    
  • }
    */

class Solution {

public:

/**
 * @param root: The root of binary tree.
 * @return: An integer
 */
int maxDepth(TreeNode *root) {
    // write your code here
    if(root == nullptr) return 0;
    else return 1 + max(maxDepth(root->left), maxDepth(root->right));
}

};
<code><pre>

相关文章

网友评论

      本文标题:Maximum Depth of Binary Tree

      本文链接:https://www.haomeiwen.com/subject/smvwettx.html