二叉树的最大深度

来源:互联网 发布:淘宝卖家小号 编辑:程序博客网 时间:2024/06/05 01:11
问题描述:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离。

样例

给出一棵如下的二叉树:

  1 / \ 2   3   / \  4   5

这个二叉树的最大深度为3.

解题思路:通过递归的方式,先求左子树的深度,再求右子树的深度,然后两者进行比较。

实验代码:

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,r;
    r=1;l=1;
    l=maxDepth(root->left)+1; 
    r=maxDepth(root->right)+1; 
    if(l>r)return l;
    else return r;..
    }
};

个人感想:递归前要判断树是否为空。如果不为空左右子树的深度初始为1。

0 0
原创粉丝点击