static TreeNode<Integer> t1;
static int leftDepth = 1;
static int rightDepth = 1;
public static void main(final String[] args) throws Exception {
initData();
int depth = caculateDepth(t1);
System.out.println(depth+"");
}
private static void initData() {
//1.父
t1 = new TreeNode<>(154);
//2.父 左
t1.addLeft(254);
//父 左 左, 父 左 右
t1.leftChild.addLeft(97);
t1.leftChild.addRight(101);
//父 左 右 左
t1.leftChild.rightChild.addLeft(66);
//父 左 右 左 左, 父 左 右 左 右
t1.leftChild.rightChild.leftChild.addLeft(33);
t1.leftChild.rightChild.leftChild.addRight(100);
//3.父 右
t1.addRight(354);
//父 右 左
t1.rightChild.addLeft(88);
}
private static int caculateDepth(TreeNode t) {
int depth = 0;
if (t != null) {
int leftDepth = caculateDepth(t.leftChild);
int rightDepth = caculateDepth(t.rightChild);
//从第一个解析,左边最大长度和右边最大长度,肯定取更长的+1
depth = leftDepth >= rightDepth ? leftDepth + 1 : rightDepth + 1;
}
return depth;
}
}
class TreeNode<T> {
T value;
TreeNode<T> leftChild;
TreeNode<T> rightChild;
TreeNode(T value) {
this.value = value;
}
TreeNode() {
}
public void addLeft(T value){
TreeNode<T> leftChild = new TreeNode<T>(value);
this.leftChild = leftChild;
}
public void addRight(T value){
TreeNode<T> rightChild = new TreeNode<T>(value);
this.rightChild = rightChild;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(!(obj instanceof TreeNode)){
return false;
}
return this.value.equals(((TreeNode<?>)obj).value);
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.value.hashCode();
}
@Override
public String toString(){
return this.value==null?"":this.value.toString();
}
2021-05-16
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 今天青石的票圈出镜率最高的,莫过于张艺谋的新片终于定档了。 一张满溢着水墨风的海报一次次的出现在票圈里,也就是老谋...