LeetCode_104_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.

題目分析:

給定一個(gè)二叉樹(shù),求出他的最大深度。
采用遞歸的方法,不斷求解l,r的深度,當(dāng)l or r = NULL時(shí) 返回 0, 每次調(diào)用遞歸函數(shù)時(shí)深度+1。并不斷取l,r的最大值。

Solution

/**
 * 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) {
        if(!root)
            return 0;
        int l = maxDepth(root->left);
        int r = maxDepth(root->right);
        
        return max(l,r)+1;
    }
};

對(duì)于遞歸掌握不是特別熟練,驗(yàn)證思路



下面以(‘x’)表示值為x的結(jié)點(diǎn)(僅針對(duì)上圖以方便表達(dá))
  maxDepth(‘5’) = max( maxDepth(‘4’), maxDepth(‘7’) )+1
  maxDepth(‘4’) = max( maxDepth(‘3’), 0 )+1
  maxDepth(‘7’) = max( maxDepth(‘2’), 0 )+1
  maxDepth(‘3’) = max( maxDepth(‘-1’), 0 )+1
  maxDepth(‘2’) = max( 0 ,0 )+1
  maxDepth(‘-1’) = max( 0, 0 )+1

所以
  maxDepth(‘-1’) = 1;
  maxDepth(‘2’) = 1;
  maxDepth(‘3’) = 2;
  maxDepth(‘7’) = 2;
  maxDepth(‘4’) = 3;
  maxDepth(‘5’) = 4;
分解為各個(gè)子樹(shù),深度求解亦正確。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容