📌  相关文章
📜  查询二叉树的两个节点之间的距离(1)

📅  最后修改于: 2023-12-03 15:10:47.512000             🧑  作者: Mango

查询二叉树的两个节点之间的距离

在二叉树中,两个节点之间的距离定义为从一个节点到另一个节点所经过的边的数量。

为了计算任意两个节点之间的距离,我们可以使用递归的方式来求解。具体思路是:对于树中的任意一个节点,我们分别计算该节点到左子树中目标节点和右子树中目标节点的距离,然后返回两个距离的和。

下面是实现该算法的一个Java代码示例:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int distanceBetweenNodes(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return 0;
        }
        if (root == p || root == q) {
            return findDepth(root, p, q);
        }
        int leftDistance = distanceBetweenNodes(root.left, p, q);
        int rightDistance = distanceBetweenNodes(root.right, p, q);
        if (leftDistance != 0 && rightDistance != 0) {
            return leftDistance + rightDistance;
        }
        return leftDistance != 0 ? leftDistance : rightDistance;
    }

    private int findDepth(TreeNode node, TreeNode p, TreeNode q) {
        if (node == null) {
            return 0;
        }
        int leftDepth = findDepth(node.left, p, q);
        int rightDepth = findDepth(node.right, p, q);
        if (node == p || node == q) {
            return Math.max(leftDepth, rightDepth) + 1;
        }
        if (leftDepth != 0 && rightDepth != 0) {
            return leftDepth + rightDepth;
        }
        return leftDepth != 0 ? leftDepth : rightDepth;
    }
}

该算法的时间复杂度为 $O(n)$,其中 $n$ 表示二叉树中节点的总数。

以上是本次介绍的主要内容,希望能对读者有所帮助。