博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
543. Diameter of Binary Tree
阅读量:2351 次
发布时间:2019-05-10

本文共 2067 字,大约阅读时间需要 6 分钟。

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:

Given a binary tree

1         / \        2   3       / \           4   5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

我的想法

bfs遍历每一个结点,对于每一个结点,dfs其左右结点并相加

class Solution {
int res; public int diameterOfBinaryTree(TreeNode root) {
if(root == null) {
return 0; } res = 0; helper(root); return res; } private void helper(TreeNode root) {
Stack
stack = new Stack<>(); stack.push(root); while(!stack.isEmpty()) {
int size = stack.size(); for(int i = 0; i < size; i++) {
TreeNode node = stack.pop(); int sum = dfs(node.left) + dfs(node.right); res = Math.max(res, sum); if(node.left != null) {
stack.push(node.left); } if(node.right != null) {
stack.push(node.right); } } } } private int dfs(TreeNode root) {
if(root == null) {
return 0; } int left = dfs(root.left); int right = dfs(root.right); return Math.max(left, right) + 1; }}

DFS已经自底向上遍历所有结点了,再来一圈BFS其实很没必要。利用res记录全局最大,返回全局最大即可

class Solution {
int res; public int diameterOfBinaryTree(TreeNode root) {
res = 0; if(root == null) {
return res; } dfs(root); return res; } private int dfs(TreeNode root) {
if(root == null) {
return 0; } int left = dfs(root.left); int right = dfs(root.right); res = Math.max(res, left + right); return Math.max(left, right) + 1; }}

解答

转载地址:http://vyqvb.baihongyu.com/

你可能感兴趣的文章
linux 知识点拾遗
查看>>
java equal和==的区别
查看>>
c++中static的用法总结
查看>>
const的常见用法
查看>>
crontab使用手册
查看>>
虚继承与虚基类的本质
查看>>
函数式编程
查看>>
GitHub上整理的一些工具
查看>>
python range 与xrange的区别
查看>>
算法-最长递增子序列
查看>>
最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
查看>>
回文字符序列
查看>>
inline函数必须在头文件中定义吗?
查看>>
内存泄漏检查工具valgrind使用方法
查看>>
Solution of Codility
查看>>
java解析XML的四种方式及比较
查看>>
单例模式(java)详细
查看>>
策略模式(java)
查看>>
java线程中信号量Semaphore类的应用
查看>>
如何设置CentOS为中文显示
查看>>