LeetCode-543. Diameter of Binary Tree (Java)
来源:互联网 发布:淘宝退款了货收到了 编辑:程序博客网 时间:2024/06/02 03:15
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].
----------------------------------------------------------------------------------------------------------------------------------------------------------
题意
求二叉树两个节点之间最长的路径。
思路
递归求解,每次返回左右子树最大长度,然后将两个最大的子树长度相加,得到二叉树节点之间最长路径。
代码
public static int diameterOfBinaryTree(TreeNode root) {if(root == null){return 0;}else{ int left = diameterOfBinaryTree(root.left); int right = diameterOfBinaryTree(root.right); //两个左右子树的最大深度相加 max = Math.max(max, left+right); //返回该节点最大的深度 return 1+Math.max(left, right);}}
阅读全文
0 0
- LeetCode-543. Diameter of Binary Tree (Java)
- 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) 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
- leetcode 543. Diameter of Binary Tree
- Leetcode 543. Diameter of Binary Tree
- [LeetCode] 543. Diameter of Binary Tree
- Leetcode-543. Diameter of Binary Tree
- bigchaindb源码分析(二)——pipeline
- C++略识之构造函数
- ACTIVEMQ设置Timestamp和jms简介
- 数组进阶对象数组
- NOIP 2004 合并果子 题解 (堆 )
- LeetCode-543. Diameter of Binary Tree (Java)
- 深入解析php中的foreach问题
- mybatis批量操作中<foreach>标签的使用
- 深入理解 Android NDK 编译(二)
- 值传递,地址传递与引用传递
- java和matlab混合编程
- Linux串口驱动程序(1)-tty架构
- PostgreSQL 数据类型介绍(三)
- 机房重构-七层登录(上)