Premiumlab  

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.

 

 

Hint:

 

Answer = max (max left_depth + max_right_depth, max left_depth, max right_depth)

 

The "max left_depth + max_right_depth" holds true when the right and left subtrees exist, and "max left_depth" holds true when only left subtree exists; likwise, "max right_depth" holds true when only right subtree exists. 

 

 

 

Back-up knowledge:

 

Q: How to calculate the depth of tree?

 

A:

1) Traverse the depth of left subtree.

2) Traverse the depth of right subtree.

3) Compare the two depths.  

If left_depth > right_depth, then return left_depth + 1.

else left_depth < right_depth, then return right_depth + 1.

 

P.S. The reason why we + 1 is that the root is at level 1. 

 

 

class Solution:
    def TreeDepth(self, node):
        if node == None:
            return 0
        left_depth = Solution.TreeDepth(self, node.left)
        right_depth = Solution.TreeDepth(self, node.right)
        return max(left_depth, right_depth) + 1

 

Note:

 

1 It is implemented in a recursive manner. 

 

 

 

Sol:

 

# 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):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max_len = 0
        def depth(node):
            if not node:
                return 0 
            left_depth = depth(node.left)
            right_depth = depth(node.right)
            self.max_len = max(self.max_len, left_depth + right_depth)
            return max(left_depth, right_depth) + 1
        depth(root)
        return self.max_len

 

 

Note:

 

1 Implant the idea of recursion in your head.  Don't think of "trace back".

 

2 self.max_len is a customer-defined variable/method. It's like "global variable", otherwise max_len can not carry the value in def depth to def diameterOfBinaryTree.  

posted on 2017-06-06 15:30  Premiumlab  阅读(132)  评论(0编辑  收藏  举报