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 = 1 Diagram of binary tree: 1 / \ 3 2 Output: 2 (or 3) Explanation: Either 2 or 3 is the closest leaf node to 1.
Example 2:
Input: root = [1], k = 1 Output: 1 Explanation: The closest leaf node is the root node itself.
Example 3:
Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2 Diagram of binary tree: 1 / \ 2 3 / 4 / 5 / 6 Output: 3 Explanation: The leaf node with value 3 (and not the leaf node with value 6) is closest to the node with value 2.
Note:
root
represents a binary tree with at least1
node and at most1000
nodes.- Every node has a unique
node.val
in range[1, 1000]
. - 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 = None
class 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))