104. Maximum Depth of Binary Tree

来源:互联网 发布:菲波那切数列python 编辑:程序博客网 时间:2024/06/06 03:48

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.

求二叉树的最大深度。

最大深度是根节点到最远叶子节点路径上经过的节点总数。


用前序遍历(DLR)

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */int maxDepth(struct TreeNode* root) {    unsigned int depth=0;    return pretrav(root,depth);}int pretrav(struct TreeNode* p, unsigned int d){    int l,r;    if(p!=NULL)                     //递归终止条件    {        d++;        l=pretrav(p->left,d);       //遍历左子树        r=pretrav(p->right,d);      //遍历右子树        d=l>=r?l:r;                 //深度为左右子树中的较大值    }    return d;}
提交结果如下:



0 0
原创粉丝点击