博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 104. Maximum Depth of Binary Tree
阅读量:4098 次
发布时间:2019-05-25

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

题目:

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.

思路:

使用递归求解非常容易,一个节点的深度等于它的左子树的深度和它的右子树的深度的最大值加上1,空树的深度是0.

代码:

/** * 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 (NULL == root){         return 0;       }       int l = maxDepth(root->left);       int r = maxDepth(root->right);       return l > r ? l + 1:r+1;     }};

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

你可能感兴趣的文章
使用SAXReader解析xml数据
查看>>
eclipse优化:每次开启eclipse都updating indexs
查看>>
eclipse编写js代码又报错:requesting java ast from selection
查看>>
java开发环境
查看>>
java开发环境
查看>>
eclipse保存卡死和内存溢出
查看>>
eclipse编写js代码又报错:requesting java ast from selection
查看>>
配置apache-maven-\conf中setting.xml文件,找到LocalRepository修改所需要的路径
查看>>
Linux防火墙通过80端口
查看>>
Linux 安装apache
查看>>
arcgis server发布地图及arcgis_js_api使用
查看>>
CESM移植
查看>>
linux解压小记
查看>>
maven 编译出错Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean
查看>>
运行报错:“tomcat” .....You must specify
查看>>
FileOutputStream
查看>>
输入输出流
查看>>
CESM移植问题小记
查看>>
NoahMP编译运行
查看>>
esmf安装问题小记
查看>>