1. 程式人生 > >資料結構---二叉樹最小深度

資料結構---二叉樹最小深度

【問題描述】: 
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

給定一個二叉樹,求出它的最小深度,最小深度是從根節點到最近的葉子節點的最短路徑的節點數。

解題思路:

以下圖為例:1:我們首先判斷是否是空樹的情況,很顯然這個不是,根節點不為空;

                     2:然後我們判斷是不是左右子樹都沒有;

                     3:然後我們判斷沒有左子樹,有右子樹的情況,然後遞迴,以此時的右子樹為根節點,從上到下繼續1,2,3操作;

                     4:然後我們判斷沒有右子樹,有左子樹的情況,然後遞迴,以此時的左子樹為根節點,從上到下繼續1,2,3,4操作;

                  5:最後左右子樹都有,我們將左右子樹看成新的樹,繼續1,2,3,4,5的操作;

下面是我在牛客網oj環境下編譯的,成功通過所有測試:

class Solution {
public:
    int run(TreeNode *root) {
        if(root==NULL)//根節點為空,即樹為空
            return 0;
        if((root->left==NULL)&&(root->right==NULL))//沒有左右樹
            return 1;
        if(root->left==NULL)//沒有左子樹,以右子樹為根,看它的左右子樹
        {
            return run(root->right)+1; //子問題,繼續遞迴
        }else if(root->right==NULL)//同上
        {
            return run(root->left)+1; 
        }else {
            return (run(root->right)<run(root->left)?run(root->right)+1:run(root->left)+1);
        }
    }
};