【leetcode】543. Diameter of Binary Tree
题目如下:
解题思路:最长的周长一定是树中某一个节点(不一定是根节点)的左右子树中的两个叶子节点之间的距离,所以最简单的办法就是把树中所有节点的左右子树中最大的两个叶子节点之间的距离求出来,最终得到最大值。
代码如下:
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): res = 0 def getLargestDis(self,node,distance): if node == None: return distance-1 else: return max(self.getLargestDis(node.left,distance+1),self.getLargestDis(node.right,distance+1)) def traverse(self,node): distance = 1 self.res = max(self.res, self.getLargestDis(node.left,distance) + self.getLargestDis(node.right,distance)) if node.left != None: self.traverse(node.left) if node.right != None: self.traverse(node.right) def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 self.res = 0 self.traverse(root) return self.res