java 树 最短路径代码_用Java实现棵普通的叉树,给定 叉树的两个节点 nodeA、nodeB,找到nodeA和nodeB的最短路径,并输出。...

展开全部

||public class Path {

public static List minPath(Node root, Node a, Node b) {

List result = new ArrayList();

if (root == null ||e69da5e6ba903231313335323631343130323136353331333361306461 a == null || b == null) {

return result;

}

List aPath = path(root, a);

List bPath = path(root, b);

int lastSameNodeIndex = getLastSameNodeIndex(aPath, bPath);

if (lastSameNodeIndex == -1) {

return result;

}

for (int i = aPath.size() - 1; i >= lastSameNodeIndex; i--) {

result.add(aPath.get(i));

}

for (int i = lastSameNodeIndex + 1; i 

result.add(bPath.get(i));

}

return result;

}

private static int getLastSameNodeIndex(List aPath, List bPath) {

int i = -1;

while (i + 1 

&& aPath.get(i + 1) == bPath.get(i + 1)) {

i++;

}

return i;

}

private static List path(Node root, Node n) {

List result = new ArrayList();

result.add(root);

if (root == n) {

return result;

}

if (root.left != null) {

List left = path(root.left, n);

if (left.size() > 0) {

result.addAll(left);

return result;

}

}

if (root.right != null) {

List right = path(root.right, n);

if (right.size() > 0) {

result.addAll(right);

return result;

}

}

result.clear();

return result;

}

}public class Node {

public char value;

public Node left;

public Node right;

public Node(char value) {

this.value = value;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值