您的位置:首页 > 其它

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.

=>所谓的深度就是指从根节点到最远的叶节点之间的距离。



/**
 * 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
执行时间还是可以接收的。



希望大家有更好的算法能够提出来,不甚感谢。



若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: