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
代码(参考:点击打开链接):
贴一下讨论区的精彩代码:点击打开链接
深度优先:
广度优先:
题目要求:
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; }
相关文章推荐
- C++ Primer Part I, 语言基础,2-7章
- function <string> std::getline (string)
- C++ 构造函数
- C++ 虚函数在基类与派生类对象间的表现及其分析
- SCPPO(六):源代码管理工具---Team Foundation Server
- 浅谈类的六个默认的成员函数
- C++ 头文件.h 源文件.cpp
- CSP考试 2015年09月第3题 模板生成系统 C++实现
- 推荐学习c语言的几个开源项目
- C++面试题(四)——智能指针的原理和实现
- 观察者模式 C++11
- C++面试题(一)——基础概念篇
- vim c语言开发配置
- vs2010,2013c++代码格式化
- 一道华为2016机试题总结:“最高分是多少”
- C修饰符const
- C++封装向量-线性表
- C/C++——strcpy函数的 几种 实现 和 详细 解析
- 【Effective C++读书笔记】篇五(条款10~条款12)
- 基于BASE64原理编码解码实现-----C语言