Maximum Depth of Binary Tree
来源:互联网 发布:基于php技术的视频直播 编辑:程序博客网 时间:2024/04/30 19:09
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.
/** * 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) { int depth = 0; queue<TreeNode *> level; if(root != NULL) level.push(root); while(!level.empty()) { depth ++; // Build the new level queue<TreeNode *> newlevel; while(!level.empty()) { TreeNode *front = level.front(); level.pop(); if(front->left != NULL) newlevel.push(front->left); if(front->right != NULL) newlevel.push(front->right); } level = newlevel; } return depth; }};
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) { if(root == NULL) return 0; int leftdepth = maxDepth(root->left); int rightdepth = maxDepth(root->right); return leftdepth > rightdepth ? leftdepth + 1 : rightdepth + 1; }};
0 0
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- linux_dhcp配置
- OC:不会说话的汤姆猫(2014年12月)未添加音频
- C语言模拟试题2
- 循环水处理剂:游泳池水处理药剂的种类
- Windbg简明教程
- Maximum Depth of Binary Tree
- WIZ珍藏 #2:来自Elecrow的 WIZnet W5200 Arduino Shield
- BZOJ 2738 矩阵乘法 整体二分+二维树状数组
- 1032. 挖掘机技术哪家强(20)
- SEO实战:需求定位提升网站排名
- duilib 修复CTreeViewUI控件动态添加子控件时,对是否显示判断不足的bug
- 循环水处理剂:室内泳池水处理药剂的选择及建议
- VC++编译器预编译头功能(stdafx.h)原理与实践
- 多线程封装