博客
关于我
Leetcode No.104 Maximum Depth of Binary Tree 遍历二叉树的深度
阅读量:356 次
发布时间:2019-03-04

本文共 1303 字,大约阅读时间需要 4 分钟。

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宏取最大值来获得最精简的代码。


转载地址:http://ltbg.baihongyu.com/

你可能感兴趣的文章
linux 的 sleep 命令
查看>>
js 的 let var const 区别
查看>>
无线掌上B超USONIX-R6线阵B模图像初步
查看>>
无线掌上B超USONIX-R6凸阵B模图像初步
查看>>
react路由使用以及封装
查看>>
vue计算属性和监听器区别
查看>>
前端常用知识随手记
查看>>
11.2.6 时间值的小数秒
查看>>
11.2.7 日期和时间类型之间的转换
查看>>
附录 B 错误信息和常见问题
查看>>
redis 内存溢出_从数据存储的角度告诉你Redis为什么这么快!
查看>>
实例分析Facebook激励视频广告接入
查看>>
实例:使用OKGO下载网络压缩包资源,然后解压缩放在本地使用
查看>>
Android主题和样式精炼详解
查看>>
HDFS Missing Block诊断信息的改进
查看>>
解决mybatis嵌套查询使用PageHelper分页不准确
查看>>
Redis源码分析(七)--- zipmap压缩图
查看>>
大规模集群自动化部署工具--Chef的安装部署
查看>>
一致性哈希算法
查看>>
HDFS源码分析(六)-----租约
查看>>