【Leetcode长征系列】Maxmium depth of binary tree
来源:互联网 发布:mac怎样删除软件 编辑:程序博客网 时间:2024/05/06 20:25
原题:
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.
这道题挺简单的,我的想法便是,对树进行递归计算高度。
如果是一棵有两个儿子的树,分别返回两个子树的高度,再加上自己已有的高度便是答案;
如果一个结点只有一个树,同样返回两个子树的高度,但为了防止出错,我们在前面会判断传递进来的节点是否为NULL,如果为NULL返回0;
如果是叶子节点,那么直接返回1
代码如下:
#include<iostream>
#include <algorithm>
/*definition for binary tree
* 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 count=1;
if (root==NULL) return 0;
if (root->right!=NULL || root->left!=NULL)
count = count + max(maxDepth(root->right),maxDepth(root->left));
else count = 1;
return count;
}
};
- 【Leetcode长征系列】Maxmium depth of binary tree
- 【Leetcode长征系列】Minimum Depth of Binary Tree
- 【Leetcode长征系列】Binary Tree Preorder Traversal
- 【Leetcode长征系列】Binary Tree Inorder Traversal
- 【Leetcode长征系列】Binary Tree Postorder Traversal
- 【Leetcode长征系列】Validate Binary Search Tree
- LeetCode: Depth of Binary Tree
- [leetcode刷题系列]Maximum Depth of Binary Tree
- [leetcode刷题系列]Minimum Depth of Binary Tree
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- 【Leetcode长征系列】Binary Tree Level Order Traversal
- 【Leetcode长征系列】Binary Tree Level Order Traversal II
- 【Leetcode长征系列】Flatten Binary Tree to Linked List
- 【Leetcode长征系列】Convert Sorted Array to Binary Search Tree
- 【Leetcode长征系列】Convert Sorted List to Binary Search Tree
- LeetCode: Minimum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- css实现下拉列表练习,原来javascipt的onmouseover和onmouseout可以用css轻松实现
- №06 视图§基础
- Android高手进阶——Adapter深入理解与优化
- 职场分享:你的职业价值观是什么
- 白霞帐冻路倨攘肯嫡冒蛹么崖嘏蓖
- 【Leetcode长征系列】Maxmium depth of binary tree
- tomcat7.0配置ssi
- 关于STM32处理器的HardFault_Handler错误原因
- NSTimeZone
- (第八天)记忆系统训练软件3.0
- javascript/js对html元素自定义属性的操作(兼容Firefox和IE)
- 多个会话修改相同行时(enq: TX-row lock contention,mode=6)
- mongodb学习笔记一:mongodb安装与介绍
- java 泛型的 设置值、取值