742. Closest Leaf in a Binary Tree

来源:互联网 发布:80年代香港女星 知乎 编辑:程序博客网 时间:2024/06/06 07:49

Given a binary tree where every node has a unique value, and a target key k, find the closest leaf node to target k in the tree.

A node is called a leaf if it has no children.

In the following examples, the input tree is represented in flattened form row by row. The actual root tree given will be a TreeNode object.

Example 1:

Input:root = [1, 3, 2], k = 1Diagram of binary tree:          1         / \        3   2Output: 2 (or 3)Explanation: Either 2 or 3 is the closest leaf node to 1.

Example 2:

Input:root = [1], k = 1Output: 1Explanation: The closest leaf node is the root node itself.

Example 3:

Input:root = [1,2,3,4,null,null,null,5,null,6], k = 2Diagram of binary tree:             1            / \           2   3          /         4        /       5      /     6Output: 3Explanation: The leaf node with value 3 (and not the leaf node with value 6) is closest to the node with value 2.

Note:

  1. root represents a binary tree with at least 1 node and at most 1000 nodes.
  2. Every node has a unique node.val in range [1, 1000].
  3. There exists some node in the given binary tree for which node.val == k.

思路:求出所有的leaf node以及root到他们的path,在求出这些path与到k的path之间的距离

# Definition for a binary tree node.class TreeNode:    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution:    def findClosestLeaf(self, root, k):        """        :type root: TreeNode        :type k: int        :rtype: int        """        if not root.left and not root.right:return root.val        leaf,path,kpath=[],[],[]        def trav(t, p):            if t.val==k:                l=list(p)                l.append(k)                kpath.append(l)            if not t.left and not t.right:                leaf.append(t)                l=list(p)                l.append(t.val)                path.append(l)                return            if t.left:                p.append(t.val)                trav(t.left, p)                p.pop()            if t.right:                p.append(t.val)                trav(t.right, p)                p.pop()        trav(root, [])                ret,min=-1,99999        kpath = kpath[0]        for p in path:            share=0            while share<len(kpath) and p[share]==kpath[share]:share+=1            if min>len(kpath)+len(p)-2*share:                min=len(kpath)+len(p)-2*share                ret=p[-1]        return ret                s =Solution()root=TreeNode(1)root.left=TreeNode(2)root.right=TreeNode(3)root.right.right=TreeNode(4)print(s.findClosestLeaf(root, 3))#print(s.findClosestLeaf([1], 1))#print(s.findClosestLeaf([1, 3, 2], 1))            


原创粉丝点击