天天看點

leetcode--104二叉樹的最大深度

給定一個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例:

給定二叉樹 [3,9,20,null,null,15,7],

3

/ \

9 20

/ \

15 7

傳回它的最大深度 3 。

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

方法:采取遞歸的方法,遞歸的終止條件是節點為空,循環的邏輯是找到左孩子的最大深度,找到右孩子的最大深度,最後取最大再加上根節點層。

代碼:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL) //循環終止條件
            return 0;
        
        int leftdepth = maxDepth(root->left);
        int rightdepth = maxDepth(root->right);
        return max( leftdepth, rightdepth) + 1;
         
    }
};