gpt4 book ai didi

algorithm - 在二叉树中找到最便宜的路径?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:45:13 25 4
gpt4 key购买 nike

我正在努力寻找解决以下问题的算法:

Given a binary tree of integers, the cost of a branch (a.k.a. a branch that starts from the root and reaches the leaf node) is given by the sum of his values. Write a function that returns a list of the cheapest branch.

Exercise

谁能推荐我完成这个练习的最简单方法?

最佳答案

可以很容易地递归完成。该函数打印所有根到叶的路径以及最便宜的分支。我使用 Arraylist 将所有节点从根节点添加到叶节点。每当到达叶节点时,我只检查到目前为止的 maxSum 是否小于当前根到叶的路径并更新它。

class Node {

public int info;
public Node left;
public Node right;

public Node(int info) {
this(info, null, null);
}

public Node(int info, Node left, Node right) {
this.info = info;
this.left = left;
this.right = right;
}

}

public class RootToLeaf {

private static int maxSum = Integer.MAX_VALUE;
private static ArrayList<Integer> finalList = new ArrayList<>();

public static void main(String[] args) {

Node root = new Node(8);
root.left = new Node(4);
root.left.left = new Node(3);
root.left.right = new Node(1);
root.right = new Node(5);
root.right.right = new Node(11);
ArrayList<Integer> list = new ArrayList<Integer>();
path(root, list,0);
System.out.println("Cheapest list is - " + finalList.toString() + " and minimum sum is " + maxSum);

}

private static void path(Node root, ArrayList<Integer> list,int s) {

if(root==null) {
return;
} else {
list.add(root.info);
s = s+root.info;
}

if ((root.left == null && root.right == null)) {
System.out.println(list);
if(maxSum>s) {
maxSum = s;
finalList = new ArrayList<>(list);
}
return;
}

path(root.left, new ArrayList<Integer>(list),s);
path(root.right, new ArrayList<Integer>(list),s);

}

}

输出结果如下:

[8, 4, 3]
[8, 4, 1]
[8, 5, 11]
Cheapest list is - [8, 4, 1] and minimum sum is 13

关于algorithm - 在二叉树中找到最便宜的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com