您的位置:首页 > 编程语言 > C语言/C++

Leetcode-104. Maximum Depth of Binary Tree c语言

2016-07-03 19:06 190 查看
来源:104. Maximum Depth of Binary Tree

题目要求:

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、首先先确定使用先序遍历来求二叉树的深度;

2、例如下图1(公3个结点)中,b作为根节点的函数记作函数1_1(由下到上,左到右,为第一层,最左边),则c作为根节点的函数1_2,然后A作为根节点的函数为函数2_1;

3、根据2的规则,图2则:D,E,B,C,A分别为函数1_1,1_2,2_1,2_2_3_1;

4、这样就考虑每次都从最里的函数考虑,即从1_*(代表1_1,1_2,1_3......)开始思考;

5、以图1为例走一遍程序(在本文后面贴上):B的左右结点都为空,故直接返回1(可以理解为出现在第一层(自下而上的数)),C的左右结点都为空,也直接返回1;

6、(补充说明:如果图1只有A,B两个结点,则j为初始值0);

7、比较左右子树,l_num>r_num?(l_num+1):(r_num+1),+1代表加上了root所在的层。

总结起来就是:由第一层,即该情况开始 root->left==NULL&&root->right==NULL开始层层而上



图1



图2
代码(参考:点击打开链接):

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
int l_num=0,r_num=0;
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
if(root->left!=NULL){
l_num=maxDepth(root->left);
}

if(root->right!=NULL){
r_num=maxDepth(root->right);
}

return l_num>r_num?(l_num+1):(r_num+1);
}


贴一下讨论区的精彩代码:点击打开链接

深度优先:

int maxDepth(TreeNode *root)
{
return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}


广度优先:

int maxDepth(TreeNode *root)
{
if(root == NULL)
return 0;

int res = 0;
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
++ res;
for(int i = 0, n = q.size(); i < n; ++ i)
{
TreeNode *p = q.front();
q.pop();

if(p -> left != NULL)
q.push(p -> left);
if(p -> right != NULL)
q.push(p -> right);
}
}

return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: