【LeetCode】Diameter of Binary Tree 解题报告
来源:互联网 发布:美图秀秀批处理mac版 编辑:程序博客网 时间:2024/05/29 11:19
【LeetCode】Diameter of Binary Tree 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/diameter-of-binary-tree/#/description
题目描述:
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.
Ways
这个题当然想到是递归。但是如何递归呢。看叶子节点的左右子树的深度都是0,那么,它的深度是0,一个数的深度是其左右子树的最大值+1。
树总的最大宽度是其左右子树高度的和中的最大值。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { int max = 0; public int diameterOfBinaryTree(TreeNode root) { DeepOfTree(root); return max; } public int DeepOfTree(TreeNode root){ if(root == null) return 0; int left = DeepOfTree(root.left); int right = DeepOfTree(root.right); max = Math.max(max, left + right); return Math.max(left, right) + 1; }}
Date
2017 年 4 月 21 日
0 0
- 【LeetCode】Diameter of Binary Tree 解题报告
- [Leetcode] 543. Diameter of Binary Tree 解题报告
- LeetCode 543. Diameter of Binary Tree 解题笔记
- Leetcode-543. Diameter of Binary Tree
- [leetcode] 543. Diameter of Binary Tree
- 【Leetcode】543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- leetcode-543. Diameter of Binary Tree
- leetcode-504-Diameter of Binary Tree
- leetcode-504-Diameter of Binary Tree
- [leetcode]-543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- (LeetCode) 543. Diameter of Binary Tree
- leetcode 543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- [leetcode]: 543. Diameter of Binary Tree
- [leetcode: Python]543. Diameter of Binary Tree
- 将二叉树拆成链表
- xlrd,xlwt模块安装
- node -v不是内部或者外部命令,也不是可执行的程序
- Java中comparable和comparator的区别
- ACM 第一天水题(3)
- 【LeetCode】Diameter of Binary Tree 解题报告
- Notepad++ 中配置Python运行环境
- 什么是base标签
- MySQL数据库简介+c语言接口+ubuntu环境
- 搜索引擎原理
- 稀疏表示与字典学习
- (原创)js提交文件,js上传文件,纯js解决无刷新文件上传,不使用form提交文件,并获取返回值(路径url)
- SSL 2294——打包
- zzuli 2129 DOBRI