LintCode 二叉树的最大深度

来源:互联网 发布:海德汉系统编程手册 编辑:程序博客网 时间:2024/06/04 23:23

题目描述:
定一个二叉树,找出其最大深度。

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

您在真实的面试中是否遇到过这个题? Yes
样例
给出一棵如下的二叉树:

1
/ \
2 3
/ \
4 5
这个二叉树的最大深度为3.

思路分析:

还是dfs 每次到叶子节点的时候,判断深度。

ac代码:

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * @param root: The root of binary tree.     * @return: An integer     */    int maxx=-1;    void dfs(TreeNode *root,int dep)    {        if(root->left==NULL && root->right==NULL)        {            if(dep>maxx)            {                maxx=dep;            }            return ;        }            if(root->left!=NULL)            {                dfs(root->left,dep+1);            }            if(root->right!=NULL)            {                dfs(root->right,dep+1);            }    }    int maxDepth(TreeNode *root) {        // write your code here        if(!root)            return 0;        dfs(root,1);        return maxx;    }};
0 0
原创粉丝点击