Maximum Depth of Binary Tree
2016-07-21 21:28
369 查看
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.
Subscribe to see which companies asked this question
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
如果二叉树为空,则深度为0
如果不为空,分别求左子树的深度和右子树的深度,去最大的再加1,因为根节点深度是1,要加进去。
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Subscribe to see which companies asked this question
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
如果二叉树为空,则深度为0
如果不为空,分别求左子树的深度和右子树的深度,去最大的再加1,因为根节点深度是1,要加进去。
/** * 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; } };
/** * 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 height(TreeNode* root) { if(root==NULL) return 0; else{ int l=height(root->left); int r=height(root->right); return 1+((l>r)?l:r); } } int maxDepth(TreeNode* root) { if (NULL == root) return 0; int l = height(root->left); int r = height(root->right); return l > r ? l + 1:r+1; } };
相关文章推荐
- Libgdx之Pixmap
- windows 堆管理
- js原生rotate函数
- java学习之路之基本语法-变量-练习题
- PAT-B 1013. 数素数
- bzoj1499(这道题改天重做,dp+单调队列优化)
- Spark总结(一)
- 源码分析-java-LinkedList
- LinkedHashMap
- 在microSD卡上扩展文件系统分区方法
- Android性能优化:谈谈Bitmap的内存管理与优化
- mysql中字符串运算
- PAT-B 1012. 数字分类
- 【经典】仙岛求药(一)
- .NET基础架构方法—DataTableToExcel通用方法
- Centos7.1 下升级内核支持aufs模块
- 145.leetcode Binary Tree Postorder Traversal(easy)[二叉树后序遍历]
- 精英币是骗人吗-精英币怎么做-精英币
- NYOJ84阶乘的0
- 训练之DP-最少拦截系统