本文主要是介绍【LeetCode】543. 二叉树的周长,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述
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.
Note: The length of path between two nodes is represented by the number of edges between them.
给定一个二叉树,你需要计算树的直径的长度。二叉树的直径是树中任意两个节点之间最长路径的长度。此路径可以通过根目录,也可以不通过根目录。
注:两个节点之间的路径长度由节点之间的边数表示。
给定一个二叉树1/ \2 3/ \ 4 5 返回 3, 为路径 [4,2,1,3] 或者 [5,2,1,3] 的长度.
Python 实现
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution(object):def diameterOfBinaryTree(self, root):""":type root: TreeNode:rtype: int"""if root == None:return 0diameter = self.maxDepth(root.left) + self.maxDepth(root.right)return max(diameter, self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right))def maxDepth(self, node):if node == None:return 0return 1 + max(self.maxDepth(node.left), self.maxDepth(node.right))
链接:https://leetcode.com/problems/diameter-of-binary-tree/
这篇关于【LeetCode】543. 二叉树的周长的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!