二叉树两个结点的最短路径

本文深入探讨了树结构中节点间距离的计算方法,包括利用最低公共祖先节点进行距离计算的公式,以及通过深度遍历和回溯法实现的两种算法方案。介绍了如何找到节点到根节点的距离,并详细阐述了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
1)node1是node2的祖先节点或孩子结点,可以理解为两个节点在一条线上。例如:Dist(2,4),Dist(6,1)
2)node1和node2没有直接或间接的父子关系。例如,Dist(4,3),他们需要一个共同的祖先结点1连接起来
假设lca是两个节点的最低公共祖先节点:leetcode 236
Dist(n1,n2)=Dist(root,n1)+Dist(root,n2)-2*Dist(root,lca)

求结点到根节点的距离

//深度遍历方法(前序遍历)
public void preOrder(TreeNode root, TreeNode node, int n) {
        if(root==null || root==node) return;
        preOrder(root.left,node,n+1);
        preOrder(root.right,node,n+1);
}
//回溯法 在list中
    public void getDistPath(TreeNode root, TreeNode node, List<TreeNode> path_list, List<List<TreeNode>> list) {
        if(root==null) return ;
        path_list.add(root);
        if(root==node) {
            list.add(new ArrayList<TreeNode>(path_list));
            return ;
        }else{
            getDistPath(root.left, node, path_list);
            getDistPath(root.right,node,path_list);
        }
        path_list.remove(path_list.size()-1);
        
    }
//回溯法 直接在path_list中
 public boolean getDistPath(TreeNode root, TreeNode node, List<TreeNode> path_list) {
        if(root==null) return false;
        path_list.add(root);
        if(root==node) return true;
        
        boolean found=false;
        //先去左子树找
        found=getDistPath(root.left, node, path_list);
        //左子树找不到去右子树找
        if(!found) found=getDistPath(root.right,node,path_list);
        //左右都找不到,弹出栈顶元素
        if(!found) path_list.remove(path_list.size()-1);
        
        return found;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值