Maximum Depth of Binary Tree--二叉树的深度
2013-10-26 22:06
274 查看
原题:
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.
=>所谓的深度就是指从根节点到最远的叶节点之间的距离。
晓东分析:
这其实是一个很基础的题目,稍微有点基础的同学应该都写过,所以也就不需要详细说明什么。这种题目使用递归的算法是最简单的,思路就是先求出左节点为根节点的二叉树的深度,再求出右节点为根节点的二叉树深度,然后看这两者谁大,大的那个加上1就是原来的二叉树的深度。
代码实现:
执行结果:
执行时间还是可以接收的。
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
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.
=>所谓的深度就是指从根节点到最远的叶节点之间的距离。
/** * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. } };
晓东分析:
这其实是一个很基础的题目,稍微有点基础的同学应该都写过,所以也就不需要详细说明什么。这种题目使用递归的算法是最简单的,思路就是先求出左节点为根节点的二叉树的深度,再求出右节点为根节点的二叉树深度,然后看这两者谁大,大的那个加上1就是原来的二叉树的深度。
代码实现:
/** * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. int left_depth = 0; int right_depth = 0; if(NULL == root) return 0; left_depth = maxDepth(root->left); right_depth = maxDepth(root->right); return left_depth > right_depth ? left_depth + 1 : right_depth + 1; } };
执行结果:
38 / 38test cases passed. | Status:Accepted |
Runtime: 44 ms |
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- Maximum Depth of Binary Tree(二叉树的最大深度)
- LeetCode | Maximum Depth of Binary Tree(二叉树的深度)
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)
- maximum-depth-of-binary-tree(二叉树的最大深度)
- Leetcode 104 Maximum Depth of Binary Tree 二叉树的最大深度
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- 【LeetCode】 Maximum Depth of Binary Tree 二叉树的最大深度 - Easy
- Maximum Depth of Binary Tree(二叉树最大深度)
- Maximum Depth of Binary Tree 二叉树的最大深度
- LinCode Maximum Depth of Binary Tree 二叉树的最大深度
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- 【LeetCode】Maximum Depth of Binary Tree (二叉树最大深度)
- lintcode maximum-depth-of-binary-tree 二叉树的最大深度
- 求二叉树的最大深度 Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree 二叉树的深度
- LeetCode OJ 之 Maximum Depth of Binary Tree (二叉树的最大深度)
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- 【LeetCode】 Maximum Depth of Binary Tree 二叉树的最大深度