742. Closest Leaf in a Binary Tree
Given a binary tree where every node has a unique value, and a target key k, find the value of the nearest leaf node to target k in the tree.
Here, nearest to a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, 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 nearest leaf node to the target of 1.
Example 2:
Input:
root = [1], k = 1
Output: 1
Explanation: The nearest 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 nearest to the node with value 2.
Note:
- root represents a binary tree with at least 1 node and at most 1000 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.
方法1:
思路:
这道题要寻找的最短路径可能是target子树内部的叶子,但也可能是某一个远房叶节点。我们如何判断和远房叶节点的距离呢?哪个节点处在最优势的位置统计这个信息?其实是target和远房叶节点的LCA,而且求LCA的过程涵盖了以上两种情况,且只能出现在target以上的位置。所以我们第一个任务是找到这些LCA。而第二个任务是对这些LCA逐一求出到自己叶子的最短距离,第三步是统计这个距离+target与LCA之后的最短距离,这时才能得到最终结果。
Complexity
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int findClosestLeaf(TreeNode* root, int k) {
stack<TreeNode*> tmp, st;
tmp.push(root);
findAncestors(tmp, k, st);
int extra = 0;
pair<int, TreeNode*> res = {INT_MAX, root};
while (!st.empty()) {
pair<int, TreeNode*> opt = {INT_MAX, root};
findLeaf(st.top(), opt, 0); st.pop();
if (opt.first + extra < res.first) {
res = opt;
}
extra++;
}
return res.second -> val;
}
void findAncestors(stack<TreeNode*> & tmp, int k, stack<TreeNode*> & st) {
if (!tmp.top()) { return; }
if (tmp.top() -> val == k) { st = tmp; return; }
tmp.push(tmp.top() -> left);
findAncestors(tmp, k, st);
tmp.pop();
tmp.push(tmp.top() -> right);
findAncestors(tmp, k, st);
tmp.pop();
return;
}
void findLeaf(TreeNode* root, pair<int, TreeNode*> & opt, int depth) {
if (!root) return;
if (!root -> left && !root -> right && depth < opt.first) {
opt = make_pair(depth, root);
return;
}
findLeaf(root -> left, opt, depth + 1);
findLeaf(root -> right, opt, depth + 1);
return;
}
};
Python
# 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: TreeNode, k: int) -> int:
def search(root):
if not root:
return False
LCA.append(root)
if root.val == k:
return True
if not search(root.left) and not search(root.right):
LCA.pop()
return False
return True
def update(root, dist):
if not root:
return
if not root.left and not root.right:
if dist < closest[0]:
closest[0] = dist
leaf[0] = root
update(root.left, dist + 1)
update(root.right, dist + 1)
LCA = []
closest, leaf = [float('inf')], [None]
to_LCA = 1
search(root)
# print([n.val for n in LCA])
update(LCA[-1], 0)
last = LCA.pop()
# print(leaf[0].val)
while LCA:
if last is LCA[-1].left:
update(LCA[-1].right, to_LCA + 1)
else:
update(LCA[-1].left, to_LCA + 1)
to_LCA += 1
last = LCA.pop()
return leaf[0].val