美文网首页
LeetCode算法解题集:Maximum Depth of B

LeetCode算法解题集:Maximum Depth of B

作者: 海阔天空的博客 | 来源:发表于2021-11-12 09:01 被阅读0次

题目:
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.

思路:
该题目是求二叉树的最大深度,分析每个节点的规律可发现明显的规律,每个节点都有左右之分,依次去求左右节点的深度即可求其最大深度。使用递归法求解。复杂度为:O(n)

代码:

/**
 * Definition for a binary tree node.
 * 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 leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
         
        return max(leftDepth, rightDepth) + 1;
    }
};

总结:
1、对于有规则的循环嵌套可以使用迭代法
2、递归法要有一个终结点,找到适当的终结点即可。如该题是 root == NULL 终结掉

本文摘录于海阔天空的博客,作者: zjg555543,发布时间: 2015-07-27

相关文章

网友评论

      本文标题:LeetCode算法解题集:Maximum Depth of B

      本文链接:https://www.haomeiwen.com/subject/nkqgoltx.html