about 35 minutes

来源: 尔思 2014-09-22 13:27:47 [] [旧帖] [给我悄悄话] 本文已被阅读: 次 (2583 bytes)
本文内容已被 [ 尔思 ] 在 2014-09-22 15:24:34 编辑过。如有问题,请报告版主或论坛管理删除.
import java.util.ArrayList;
import java.util.List;

class Tree {
public int x;
public Tree l;
public Tree r;

public Tree(int x) {
this.x = x;
l = null;
r = null;
}
}

class IntPair {
public int min;
public int max;

public IntPair(int min, int max) {
this.min = min;
this.max = max;
}

public String toString() {
return String.format("(%d, %d)", min, max);
}
}

public class Solution {

List pathPairs = null;

public TreeAmplitude() {
pathPairs = new ArrayList();
}

public int solution(Tree t) {

pathPairs.clear();

amplitude(t, new IntPair(1000000000, -1000000000));

int max = -1000000000;
IntPair p = null;
for (int i = 0; i < pathPairs.size(); i++) {
p = pathPairs.get(i);
System.out.println(p);
max = ((p.max - p.min) > max) ? (p.max - p.min) : max;
}

System.out.println("max = " + max);

return max;

}

private void amplitude(Tree t, IntPair p)
{
if ( t == null ) { return; }

int min = p.min < t.x ? p.min : t.x;
int max = p.max > t.x ? p.max : t.x;
IntPair minMax = new IntPair(min, max);

if (t.l == null && t.r == null) {
pathPairs.add(minMax);
}

if (t.l != null) {
amplitude(t.l, minMax);
}

if (t.r != null) {
amplitude(t.r, minMax);
}

}

public static void main(String[] args) {

Tree t5 = new Tree(5);
Tree t8 = new Tree(8);
Tree t9 = new Tree(9);
Tree t12 = new Tree(12);
Tree t2 = new Tree(2);
Tree t8_ = new Tree(8);
Tree t4 = new Tree(4);
Tree t2_ = new Tree(2);
Tree t5_ = new Tree(5);

t5.l = t8; t5.r = t9;
t8.l = t12; t8.r = t2;
t9.l = t8_; t9.r = t4;
t8_.l = t2_; t4.r = t5_;

Soultion ta = new Solution();
ta.solution(t5);

}

所有跟帖: 

Good job. I will test code later. -delta101- 给 delta101 发送悄悄话 (0 bytes) () 09/22/2014 postreply 18:58:31

请您先登陆,再发跟帖!

发现Adblock插件

如要继续浏览
请支持本站 请务必在本站关闭/移除任何Adblock

关闭Adblock后 请点击

请参考如何关闭Adblock/Adblock plus

安装Adblock plus用户请点击浏览器图标
选择“Disable on www.wenxuecity.com”

安装Adblock用户请点击图标
选择“don't run on pages on this domain”