Depth-first Search

這個題目用到深度優先搜索。
深度的定義是:

對任意節點n,n的深度是根節點到n的路徑長。

對于樹和圖的特性,首先想到的就是用遞歸,因為他們總能拆分成同樣結構的更小的問題。
我想求根節點的深度,這個深度就等于略大的那顆子樹的深度+1。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int reTraversal(struct TreeNode* root, int n)
{
    /* data */
    int iLeft = 0;
    int iRight = 0;
    if (root->left == NULL && root->right == NULL)
    {
        /* code */
        return n;
    }

    if (root->left != NULL)
    {
        /* code */
        iLeft = reTraversal(root->left, n+1);
    }
    if (root->right != NULL)
    {
        /* code */
        iRight = reTraversal(root->right, n+1);
    }
    return iLeft > iRight ? iLeft : iRight ;
}

int maxDepth(struct TreeNode* root) {

    int iDepth = 0;
    if (root == NULL)
    {
        /* code */
        return 0;
    }
    // return maxDepth(root->left) >= maxDepth(root->right) ? 1+maxDepth(root->left):1+ maxDepth(root->right);
    iDepth = reTraversal(root,1);
    return iDepth;
}

return maxDepth(root->left) >= maxDepth(root->right) ? 1+maxDepth(root->left):1+ maxDepth(root->right);
這一行是我第一次的提交的代碼,通過了大多數的case,但是如果樹很大就陷入了死循環。

于是第二次提交就把這個思路拆分了一下。
先求左樹的深度,在求右樹的深度.

類似的題目中,求樹的最小值,其中有一個情況需要考慮一下,就是

特殊場景.001.jpeg

在另一個孩子為空的時候不能返回0.所以在遍歷的時候最后加上限制條件

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
 
int reTraversal(struct TreeNode* root, int n)
{
    /* data */
    int iLeft = 0;
    int iRight = 0;
    if (root->left == NULL && root->right == NULL)
    {
        /* code */
        return n;
    }

    if (root->left != NULL)
    {
        /* code */
        iLeft = reTraversal(root->left, n+1);
    }
    if (root->right != NULL)
    {
        /* code */
        iRight = reTraversal(root->right, n+1);
    }
    //特殊場景處理的片段
    if(iLeft != 0 && iRight != 0)
    {
        return iLeft > iRight ? iRight  : iLeft ;
    }
    else
    {
        return iLeft == 0 ? iRight : iLeft;
    }
    
}
int minDepth(struct TreeNode* root) {
    int iDepth = 0;
    if (root == NULL)
    {
        /* code */
        return 0;
    }
    // return maxDepth(root->left) >= maxDepth(root->right) ? 1+maxDepth(root->left):1+ maxDepth(root->right);
    iDepth = reTraversal(root,1);
    return iDepth;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容