【對遞歸的理解】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.

求一棵二叉樹的最大深度,利用遞歸實現。代碼如下:

/**
 * Definition for binary tree
 * 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 == NULL){
            return 0;
        }
        int leftMax = maxDepth(root->left);
        int rightMax = maxDepth(root->right);
        if(leftMax >= rightMax){
            return leftMax+1;
        }
        else{
            return rightMax+1;
        }
    }
};
遞歸程序調用過程分析如下:

以一個非常簡單的二叉樹作爲示例,第一次進入遞歸函數時,用單箭頭表示。返回時用雙箭頭表示並用ret加上返回值返回。具體調用過程見下圖:


總結:

1. 要有能使遞歸終止的條件,否則將一直執行下去;

2.每一層次的遞歸函數調用都會有本層次遞歸函數的局部變量,再遇到返回條件時反方向向前返回值。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章