104. Maximum Depth of Binary Tree
来源:互联网 发布:ip网络广播问题解决 编辑:程序博客网 时间:2024/05/17 01:50
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:dfs递归求解
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(root == NULL)return 0; int res = INT_MIN; dfs(root, 1, res); return res; } void dfs(TreeNode *root, int depth, int &res) { if(root->left == NULL && root->right == NULL && res < depth) {res = depth; return;} if(root->left) dfs(root->left, depth+1, res); if(root->right) dfs(root->right, depth+1, res); }};
算法2:层序遍历,树的总层数就是树的最大高度
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. //层序遍历计算树的层数即可,NULL作为每一层节点的分割标志 if(root == NULL)return 0; int res = 0; queue<TreeNode*> Q; Q.push(root); Q.push(NULL); while(Q.empty() == false) { TreeNode *p = Q.front(); Q.pop(); if(p != NULL) { if(p->left)Q.push(p->left); if(p->right)Q.push(p->right); } else { res++; if(Q.empty() == false)Q.push(NULL); } } return res; }};
0 0
- [LeetCode]104.Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- [Leetcode] 104. Maximum Depth of Binary Tree
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode:104. Maximum Depth of Binary Tree
- (15.1.11.2)听力之短文理解
- Java实现算法之--选择排序
- MFC:只允许产生一个应用程序实例的具体实现
- 数据库事务
- 排序算法(五)——快速排序
- 104. Maximum Depth of Binary Tree
- 剑指offer_面试题15_链表中倒数第k个节点(考虑问题要全面)
- BOOKSTORE OPENCART 自适应主题模板 ABC-0109
- 分类(类目)及类扩展
- Single Number
- android图片的异步加载和双缓存学习笔记——DisplayImageOptions
- 一周心结总,拨开云雾见青天
- 让多个Fragment 切换时不重新实例化
- JavaScript对象、函数(你不知道的JavaScript)