The nearest common ancestor of a binary tree [Java implementation]

Question description

There is a binary tree with n nodes (the node numbers are from 0 to n-1, the root node The node is node numbered 0), find the nearest common ancestor of the two nodes with specified numbers.

Note: The nearest common ancestor of two nodesA、B on the binary tree refers to: a nodeP that exists on the binary tree, such that needs to be as far away from the root node as possible far (that is, the layer number is as large as possible). , and and the ancestor of P is both the ancestor of ABP

Enter description

The first line3 integersn、k1、k2(1≤n≤50,0≤k1≤n−1,0≤k2≤n−1) respectively represent the number of nodes of the binary tree and the numbers of the two nodes whose nearest common ancestors need to be found. ;

The next linesn, each line has one node, and the numbers from 0 to n-1 are given in order The left child node number and the right child node number of the node, separated by spaces. If there is no corresponding child node, it is represented by -1.

Output description

Outputs an integer representing the number of the most recent common ancestor.

Sample

enter

6 1 4			// 共有6个节点【编号0~5】,目标节点编号为1和4
2 5			// 0号节点的左节点为2号节点,右节点为5号节点
-1 -1		// 1号节点左右节点都为空
1 4			// 2号节点左节点为1号节点,右节点为4号节点
-1 -1		// ...依次类推
-1 -1
-1 3
image-20230305170515544

output

2	// 1号节点和4号节点在上述树结构中的祖先节点为2号节点

Idea analysis

  • The so-called ancestor node must be our target node or its upper level, that is, we have to traverse the lower part of the current node , to determine whether the current node is an ancestor node.

    Among the three traversals of the tree, it is obvious to complete the following traversal first and then judge the current node. It is post-order traversal. Determining the traversal method is the first step in solving the problem.

  • The second step issetting up boundaries, that is, how to determine whether the current node is an ancestor node, or how to determine that it is definitely not an ancestor node a>

    1. If the current nodeleft subtree parthas a target node,right subtree partThere is also a target node, so it can be determined that the current node must be an ancestor node
    2. If the current node is the target node, and there is also a target node in the left and right subtrees, it can be determined that the current node must be the ancestor node
    3. Except for the above two cases, all other cases are non-ancestor nodes.
  • After clarifying the steps, the function we design should return the left and right subtrees of the current node or whether it contains the target node. If it does, it will returntrue, if it does not, it will returnfalse, and record the ancestor nodes that meet the conditions during the post-order traversal process.

Code

package homework;

import java.util.Scanner;


public class Main {
    
    
	static int ans = -1;

	public static void main(String[] args) {
    
    
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		TreeNode arrs[] = new TreeNode[n];
		int k1 = scanner.nextInt();
		int k2 = scanner.nextInt();
		for (int i = 0; i < n; i++) {
    
    
			TreeNode node = new TreeNode();
			node.left = scanner.nextInt();
			node.right = scanner.nextInt();
			arrs[i] = node;
		}
		findAncestorByPostOrder(arrs, 0, k1, k2);
		System.out.println(ans);

	}

	public static boolean findAncestorByPostOrder(TreeNode arrs[], int index, int k1, int k2) {
    
    
		if (index == -1) {
    
    
			return false;
		}
		boolean left = findAncestorByPostOrder(arrs, arrs[index].left, k1, k2);
		boolean right = findAncestorByPostOrder(arrs, arrs[index].right, k1, k2);
		// 说明当前节点是目标之一
		boolean flag = index == k1 || index == k2;
		// 当前节点为目标节点主要对应如下两种情况:
		// 1. 当左右同时为目标;
		// 2. 当左边或者右边有一个为目标,且当前也是目标之一
		if ((left && right) || ((left || right) && flag)) {
    
    
			ans = index;
		}
		// 如果当前节点左右存在目标节点,或者当前节点就是目标节点时返回 true
		return left || right || flag;
	}

}

class TreeNode {
    
    
	int left;
	int right;


}

Guess you like

Origin blog.csdn.net/weixin_45488428/article/details/129348409