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,但是如果树很大就陷入了死循环。

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

类似的题目中,求树的最小值,其中有一个情况需要考虑一下,就是

《Depth-first Search》 特殊场景.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;
}
    原文作者:宇文黎琴
    原文地址: https://www.jianshu.com/p/8481afa5bc4c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞