leetcode 104求二叉树的最大深度
2017-11-11 14:08
399 查看
/**
* 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(root==NULL)
{
return 0;
}
int leftdepth=maxDepth(root->left);
int rightdepth=maxDepth(root->right);
return (leftdepth>rightdepth?leftdepth+1:rightdepth+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(root==NULL)
{
return 0;
}
int leftdepth=maxDepth(root->left);
int rightdepth=maxDepth(root->right);
return (leftdepth>rightdepth?leftdepth+1:rightdepth+1);
}
};
思路:
通过递归遍历
首先确定大概思想,根节点不为空就是比较左右子树大小,取大的加一,然后传入左右孩子节点地址进行递归。
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- 二叉树的最大深度(leetcode-104)
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- Leetcode 104 Maximum Depth of Binary Tree 二叉树的最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [LeetCode] 104 二叉树最大深度
- [LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)
- [LeetCode]104. Maximum Depth of Binary Tree--二叉树的最大深度
- [LeetCode] Maximum Depth of Binary Tree 二叉树的最大深度
- leetCode 104.Maximum Depth of Binary Tree(二叉树最大深度) 解题思路和方法
- Leetcode 95. Unique Binary Search Trees II及二叉树最大最小深度镜像树总结
- [Leetcode] Maximum depth of binary tree二叉树的最大深度
- LeetCode 104. 二叉树的最大深度
- 每天一道LeetCode-----计算二叉树的最大深度及最小深度,判断二叉树是否是高度平衡二叉树
- LeetCode 刷题之二:寻找二叉树的最大深度
- leetcode 662. Maximum Width of Binary Tree 二叉树最大宽度 + 深度优先遍历DFS