PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000027. Tổ tiên chung trên cây nhị phân (Lowest Common Ancestor of a Binary Tree)
HỌC THEO LỘ TRÌNH
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
Tổ tiên chung trên cây nhị phân (Lowest Common Ancestor of a Binary Tree)
Lowest Common Ancestor of a Binary Tree
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
A binary tree has vertices indexed through . Each vertex has at most one left and one right child, without the BST ordering restriction. Given two existing vertices , find their lowest common ancestor: the deepest vertex lying on both root-to-vertex paths. A vertex counts as its own ancestor.
The original LeetCode function interface is converted into an indexed-tree input/output interface for PHOJ.
Input
- First line: , number of vertices and root index.
- For each vertex , the next line contains its left and right child indices;
0means absent. - Last line gives vertex indices .
Output
Print the lowest common ancestor vertex index.
Subtasks
General constraints (all subtasks): ; ; .
- Subtask 1 (20 points): ; .
- Subtask 2 (30 points): ; .
- Subtask 3 (50 points): ; .
Examples
Input
5 1
2 3
4 5
0 0
0 0
0 0
4 5
Output
2
Explanation
Vertices and share parent , so their lowest common ancestor is .