DS树+图综合练习--二叉树高度
题目描述
给出一棵二叉树,求它的高度。二叉树的创建采用前面实验的方法。
注意,二叉树的层数是从1开始
输入
第一行输入一个整数t,表示有t个二叉树
第二行起输入每个二叉树的先序遍历结果,空树用字符‘0’表示,连续输入t行
输出
每行输出一个二叉树的高度
样例输入
1
AB0C00D00
样例输出
3
提示
import java.util.*;
/**
* @author: Liu Canbin
* @date: 2019/1/4
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i <n ; i++) {
String s = scanner.next();
Tree tree = new Tree();
tree.create(s);
tree.treeDepthShow();
// System.out.println();
}
}
}
class Node
{
char data;
Node left;
Node right;
Node(char ch){
data =ch;
left = null;
right = null;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
}
class Tree{
Node root;
int pos;
String strTree;
int sum;
void create(String s){
pos = 0;
strTree = s;
sum =0;
root =createTree();
}
Node createTree(){
Node t;
char ch = strTree.charAt(pos++);
if (ch=='0'){
t = null;
}else {
t = new Node(ch);
t.setLeft(createTree());
t.setRight(createTree());
}
return t;
}
void treeDepthShow() {
System.out.println(treeDepth(root));
}
private int treeDepth(Node t){
if (t==null){
return 0;
}
int left = treeDepth(t.left);
int right = treeDepth(t.right);
return left>right?left+1:right+1;
}
}