543. Diameter of Binary Tree

Posted johnnyzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了543. Diameter of Binary Tree相关的知识,希望对你有一定的参考价值。

/**
*543. Diameter of Binary Tree
* https://leetcode.com/problems/diameter-of-binary-tree/description/
* */

class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}

//一般树的题:
//时间复杂度:O(n),因为每个节点都要访问一次
//空间复杂度:O(h),如果用递归的话,需要入stack,所以根据树的高度定义stack的深度
class Solution {
var answer = 0
//每条边只能调用一次
fun diameterOfBinaryTree(root: TreeNode?): Int {
if (root == null) {
return 0
}
//递归方式,非递归的可以试
diameterHelp(root)
return answer
}

private fun diameterHelp(root: TreeNode?): Int {
if (root == null) {
return -1
}
val l = diameterHelp(root.left) + 1
val r = diameterHelp(root.right) + 1
//
answer = Math.max(answer, l + r)
return Math.max(l, r)
}
}

以上是关于543. Diameter of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

543. Diameter of Binary Tree

Leetcode-543-Diameter of Binary Tree

543. Diameter of Binary Tree

543. Diameter of Binary Tree

543. Diameter of Binary Tree

543. Diameter of Binary Tree