C++詳解Leetcode:104. Maximum Depth of Binary Tree

原題

這裏寫圖片描述

思路

此題就是計算二叉樹的最大深度,通過遞歸可以很輕鬆的進行處理

code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
         int ldepth, rdepth;
        if (root != NULL)
        {
            ldepth = maxDepth(root->left);
            rdepth = maxDepth(root->right);
            if (ldepth > rdepth)
            {
                return ldepth + 1;
            }
            else
            {
                return rdepth + 1;
            }
        }
        else
        {
            return 0;
        }
    }
};
發佈了117 篇原創文章 · 獲贊 82 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章