二叉树的最大深度
2017-04-15 17:51
176 查看
问题描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离
解题思路:分别遍历左右的子树,然后比较左右子树的深度,返回较大的那个
实现代码:class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if(root==NULL){
return 0;
}
int l = maxDepth(root->left);
int r = maxDepth(root->right);
if(l>r){
return l+1;
}
else {
return r+1;
}
}
};
感悟:跟遍历子树差不多吧,就多了一步比较。
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离
解题思路:分别遍历左右的子树,然后比较左右子树的深度,返回较大的那个
实现代码:class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if(root==NULL){
return 0;
}
int l = maxDepth(root->left);
int r = maxDepth(root->right);
if(l>r){
return l+1;
}
else {
return r+1;
}
}
};
感悟:跟遍历子树差不多吧,就多了一步比较。
相关文章推荐
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [Leetcode] Maximum depth of binary tree二叉树的最大深度
- LintCode:二叉树的最大深度
- Leetcode 104 Maximum Depth of Binary Tree 二叉树的最大深度
- E 二叉树最大深度
- LintCode-97.二叉树的最大深度
- 非递归求取二叉树的最大/小深度
- 二叉树的最大深度 & 二叉树的最小深度
- 二叉树最大深度和最小深度
- LeetCode----Maximum Depth of Binary Tree 求二叉树最大深度
- lintcode——二叉树的最大深度
- 【LeetCode笔记】Maximum Depth of Binary Tree 二叉树最大深度 递归&非递归
- 【leetcode Java】二叉树的递归遍历以及最大深度的求解(Java)
- Google算法题:二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度算法面试题-leetcode学习之旅(3)
- 二叉树的最大深度
- Leetcode 104.Maximum Depth of Binary Tree (二叉树的最大深度)
- 求二叉树的最小深度和最大深度
- Java实现二叉树的先序、中序、后序、层次遍历,数的最大深度、最大宽度