leetcode 543. Diameter of Binary Tree

 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. 

涉及到tree的题目无非是遍历,三种遍历你要非常熟悉,本题目是后序遍历,你自己在头脑中自底向上模拟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):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        """
          1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 

1 => 1 [1]
[1, 2]=>2
          1
         / \
        2   3 => 3 left max(no root) + right max(no root), the path pass root(root.left.depth ,root.right.depth) or not???

          1
         / \
        2   3
       / \     
      4   5    
      => recursively      
        """
        
        def get_depth_and_diameter(node):
            if not node: return 0, 0
            l_height, l_diameter = get_depth_and_diameter(node.left)
            r_height, r_diameter = get_depth_and_diameter(node.right)
            return (1+max(l_height, r_height), max(l_diameter, r_diameter, l_height+r_height))
        
        return get_depth_and_diameter(root)[1]
        

也可以在迭代每一个node的时候,记录下其diameter,ans就是所有node diameter最大值:

# 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
        """               
        ans = 0
        def get_depth(node):
            if not node: return 0
            l = get_depth(node.left)
            r = get_depth(node.right)
            nonlocal ans
            ans = max(ans, l+r)            
            return 1+max(l, r)
        
        get_depth(root)
        return ans
        

还有就是重复遍历tree node,其实你可以想想,本质上重复遍历是可以变为一次遍历,只是返回多个值而已,或者是用状态变量记录多个状态!

public class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null){
            return 0;
        }
       int dia = depth(root.left) + depth(root.right);
       int ldia = diameterOfBinaryTree(root.left);
       int rdia = diameterOfBinaryTree(root.right);
       return Math.max(dia,Math.max(ldia,rdia));
        
    }
    public int depth(TreeNode root){
        if(root == null){
            return 0;
        }
        return 1+Math.max(depth(root.left), depth(root.right));
    }
    
}

 

当年谷歌面试失败,求解所有path的代码:

# 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
        """               
        ans = [[]]
        
        def get_max_depth_path(node): 
            if not node: return [[]]
            l = get_max_depth_path(node.left)
            r = get_max_depth_path(node.right)
            
            nonlocal ans
            if len(l[0]) + len(r[0]) + 1 == len(ans[0]):
                ans.append([n1+[node]+n2 for n1 in l for n2 in r])
            elif len(l[0]) + len(r[0]) + 1 > len(ans[0]):
                ans = [n1+[node]+n2 for n1 in l for n2 in r]                   
                
            if len(l[0]) > len(r[0]):
                return [path+[node] for path in l]
            elif len(l[0]) < len(r[0]):
                return [path+[node] for path in r]
            else:
                return [path+[node] for path in l+r]
        
        #if not root: return 0
        get_max_depth_path(root)
        #return len(ans[0])-1     
     return ans

 

posted @ 2018-04-02 23:20  bonelee  阅读(307)  评论(1编辑  收藏  举报