返回介绍

solution / 0700-0799 / 0742.Closest Leaf in a Binary Tree / README_EN

发布于 2024-06-17 01:03:34 字数 7082 浏览 0 评论 0 收藏 0

742. Closest Leaf in a Binary Tree

中文文档

Description

Given the root of a binary tree where every node has a unique value and a target integer k, return _the value of the nearest leaf node to the target _k_ in the tree_.

Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.

 

Example 1:

Input: root = [1,3,2], k = 1
Output: 2
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
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.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • 1 <= Node.val <= 1000
  • All the values of the tree are unique.
  • There exist some node in the tree where Node.val == k.

Solutions

Solution 1

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def findClosestLeaf(self, root: TreeNode, k: int) -> int:
    def dfs(root, p):
      if root:
        g[root].append(p)
        g[p].append(root)
        dfs(root.left, root)
        dfs(root.right, root)

    g = defaultdict(list)
    dfs(root, None)
    q = deque([node for node in g if node and node.val == k])
    seen = set()
    while q:
      node = q.popleft()
      seen.add(node)
      if node:
        if node.left is None and node.right is None:
          return node.val
        for next in g[node]:
          if next not in seen:
            q.append(next)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  private Map<TreeNode, List<TreeNode>> g;

  public int findClosestLeaf(TreeNode root, int k) {
    g = new HashMap<>();
    dfs(root, null);
    Deque<TreeNode> q = new LinkedList<>();
    for (Map.Entry<TreeNode, List<TreeNode>> entry : g.entrySet()) {
      if (entry.getKey() != null && entry.getKey().val == k) {
        q.offer(entry.getKey());
        break;
      }
    }
    Set<TreeNode> seen = new HashSet<>();
    while (!q.isEmpty()) {
      TreeNode node = q.poll();
      seen.add(node);
      if (node != null) {
        if (node.left == null && node.right == null) {
          return node.val;
        }
        for (TreeNode next : g.get(node)) {
          if (!seen.contains(next)) {
            q.offer(next);
          }
        }
      }
    }
    return 0;
  }

  private void dfs(TreeNode root, TreeNode p) {
    if (root != null) {
      g.computeIfAbsent(root, k -> new ArrayList<>()).add(p);
      g.computeIfAbsent(p, k -> new ArrayList<>()).add(root);
      dfs(root.left, root);
      dfs(root.right, root);
    }
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  unordered_map<TreeNode*, vector<TreeNode*>> g;

  int findClosestLeaf(TreeNode* root, int k) {
    dfs(root, nullptr);
    queue<TreeNode*> q;
    for (auto& e : g) {
      if (e.first && e.first->val == k) {
        q.push(e.first);
        break;
      }
    }
    unordered_set<TreeNode*> seen;
    while (!q.empty()) {
      auto node = q.front();
      q.pop();
      seen.insert(node);
      if (node) {
        if (!node->left && !node->right) return node->val;
        for (auto next : g[node]) {
          if (!seen.count(next))
            q.push(next);
        }
      }
    }
    return 0;
  }

  void dfs(TreeNode* root, TreeNode* p) {
    if (!root) return;
    g[root].push_back(p);
    g[p].push_back(root);
    dfs(root->left, root);
    dfs(root->right, root);
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func findClosestLeaf(root *TreeNode, k int) int {
  g := make(map[*TreeNode][]*TreeNode)
  var dfs func(root, p *TreeNode)
  dfs = func(root, p *TreeNode) {
    if root == nil {
      return
    }
    g[root] = append(g[root], p)
    g[p] = append(g[p], root)
    dfs(root.Left, root)
    dfs(root.Right, root)
  }
  dfs(root, nil)
  var q []*TreeNode
  for t, _ := range g {
    if t != nil && t.Val == k {
      q = append(q, t)
      break
    }
  }
  seen := make(map[*TreeNode]bool)
  for len(q) > 0 {
    node := q[0]
    q = q[1:]
    seen[node] = true
    if node != nil {
      if node.Left == nil && node.Right == nil {
        return node.Val
      }
      for _, next := range g[node] {
        if !seen[next] {
          q = append(q, next)
        }
      }
    }
  }
  return 0
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文