二叉树的最大深度
2017-04-11 17:03
148 查看
1.问题描述:给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的距离。
2.思路:正如样例
给出一棵如下的二叉树:
这个二叉树的最大深度为
利用递归的思想,不断求左右子树的深度,最终最大的那个+1就是给定二叉树的最大深度。
3.代码:
4.感想:像二叉树的前、中、后序遍历一样,运用了递归的思想,这样大大简便了题目!
2.思路:正如样例
给出一棵如下的二叉树:
1 / \ 2 3 / \ 4 5
这个二叉树的最大深度为
3
利用递归的思想,不断求左右子树的深度,最终最大的那个+1就是给定二叉树的最大深度。
3.代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ 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); int a=max(l,r)+1; return a; } };
4.感想:像二叉树的前、中、后序遍历一样,运用了递归的思想,这样大大简便了题目!
相关文章推荐
- 二叉树最大深度的值
- 二叉树的最大深度和最小深度
- 二叉树的最大深度(leetcode-104)
- Maximum Depth of Binary Tree 二叉树的最大深度
- [LeetCode] 104 二叉树最大深度
- 二叉树的最大深度
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- Leetcode 95. Unique Binary Search Trees II及二叉树最大最小深度镜像树总结
- 97 - 二叉树的最大深度
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- Maximum Depth of Binary Tree --- 求二叉树的最大深度
- 求一棵二叉树的最大深度
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- LeetCode OJ 之 Maximum Depth of Binary Tree (二叉树的最大深度)
- [LeetCode]104. Maximum Depth of Binary Tree(二叉树最大深度)
- leetCode 104.Maximum Depth of Binary Tree(二叉树最大深度) 解题思路和方法
- 【简单算法】26. 二叉树的最大深度
- 二叉树的最大深度
- Leetcode 104.Maximum Depth of Binary Tree (二叉树的最大深度)
- [LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)