使用最少的钱切割金条
哈夫曼编码
最小生成树
比如现在数组里的数为 1,4,6,8,3,9.
先把这个数组中的数组成一个小根堆,
每次将最小的两个数弹出,相加,再放回去。每次累计相加结果
直到这个里只有一个数。
那么累加结果就是要找的最小代价。
public static int lessMoney(int[] arr) {
PriorityQueue<Integer> pQ = new PriorityQueue<>();
for (int i = 0; i < arr.length; i++) {
pQ.add(arr[i]);
}
int sum = 0;
int cur = 0;
while (pQ.size() > 1) {
cur = pQ.poll() + pQ.poll();
sum += cur;
pQ.add(cur);
}
return sum;
}
public static void main(String[] args) {
// solution
int[] arr = { 10, 20, 30};
System.out.println(lessMoney(arr));
}
二叉树的三序遍历的非递归实现
使用堆结构可以很快的解决此问题。
先序 根、左、右
使用一个栈,将第一个节点压入,如果栈顶元素的孩子指针域不为空,弹出第一个节点,遍历第一个节点的左右孩子,如果有右孩子先压入右孩子,再压入左孩子。然后再判断栈顶的元素。先放右再放左。
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
public static void preOrderUnRecur(Node head) {
System.out.print("pre-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.print(head.value + " ");
if (head.right != null) {
stack.push(head.right);
}
//先序遍历时,左子树先输出,所以应该先加入右子树的节点。(栈是先进后出)
if (head.left != null) {
stack.push(head.left);
}
}
}
System.out.println();
}
中序 左 根 右
使用一个栈,将头节点压入栈,然后一直遍历他的左孩子,直到左孩子为空。弹出此时的栈顶元素,将指针指向刚才节点的右孩子,如果右孩子为空,弹出栈顶元素, 将指针指向刚才弹出元素的右孩子,继续这个过程。
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
public static void inOrderUnRecur(Node head) {
System.out.print("in-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
// 一直将左节点放入栈中
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
后序 左 右 根
先序的顺序是 根 左 右,将 先序改造为 根 右 左。然后将打印出来的数放到另一个栈里,那么真正的输出顺序就是 左 右 根 也就是后序遍历的顺序。
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
public static void posOrderUnRecur1(Node head) {
System.out.print("pos-order: ");
if (head != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while (!s1.isEmpty()) {
head = s1.pop();
s2.push(head);
if (head.left != null) {
s1.push(head.left);
}
if (head.right != null) {
s1.push(head.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
}
System.out.println();
}