Leetcode No.104 Maximum Depth of Binary Tree 遍历二叉树的深度

本文探讨了如何求解二叉树的最大深度问题,并提供了两种不同的C++实现方案。一种是通过递归遍历的方式逐步深入节点并记录深度,另一种则是更简洁的递归解法,利用return语句直接计算左右子树的最大深度。

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.


注:题库和图片转自 www.leetcode.com ,所有权归www.leetcode.com仅供交流学习使用,不得用于商业用途

-----------------------------------------------------------------------------------------------------

我的解法:

/**
 * 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) {
        int currentDepth = 0;
        maxDep = 0;
        if(root != NULL)
        {
            travelBinaryTree(root, currentDepth);
        }
        return maxDep;
    }
private:
    int maxDep;
    void travelBinaryTree(TreeNode* node, int depth)
    {
        depth++;
        maxDep = (depth > maxDep) ? depth : maxDep;
        if(node->left)
            travelBinaryTree(node->left, depth);
        if(node->right)
            travelBinaryTree(node->right, depth);
    }
};

虽然结果正确,看了一下bbs上的讨论,感觉算法虽然不复杂但是太多代码冗余,leetcode上比较精简的一种解法

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root)
            return 0;
        return 1 + max(maxDepth(root->right), maxDepth(root->left));
    }
};

利用return的时候累加+1和max宏取最大值来获得最精简的代码。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值