LeetCode 104 二叉树的最大深度
2019-03-04 10:14
288 查看
- 题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
- 解题思路:
1.自顶向下递归:
代码实现:
int res = 0; int maxDepth(TreeNode* root) { if(!root) return res; int depth = 1; max1(root, depth); return res; } void max1(TreeNode* root, int depth) { if(!root) return ; res = max(res,depth); max1(root->left, depth+1); max1(root->right, depth+1); }
2.自下向上
代码实现:
int maxDepth(TreeNode* root) { if(!root) return 0; int max1 = maxDepth(root->left); int max2 = maxDepth(root->right); return max1 > max2? max1+1: max2+1; }
相关文章推荐
- LeetCode104--二叉树最大深度
- [LeetCode] 104 二叉树最大深度
- LeetCode 104--二叉树的最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- LeetCode-104.二叉树的最大深度(相关话题:递归)
- 二叉树的最大深度(leetcode-104)
- Leetcode 104 Maximum Depth of Binary Tree 二叉树的最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- 【LeetCode】[104] 二叉树的最大深度——“递归”
- leetcode 104求二叉树的最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- [LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)
- 104. 二叉树的最大深度
- Leetcode 95. Unique Binary Search Trees II及二叉树最大最小深度镜像树总结
- 【LeetCode】104. Maximum Depth of Binary Tree 求解二叉树最大深度
- 【LeetCode笔记】Maximum Depth of Binary Tree 二叉树最大深度 递归&非递归