欢迎关注我的B站账号:卍卍子非鱼卍卍
二叉树
二叉树的构造
现有格式化字符串str = "A(B(D(,G)),C(E,F))"
其中每一个字母代表一个节点的值,字母后面的括号"()"
代表它的子树,其中逗号","
前为左子树,逗号","
后为右子树。
上述字符串str
构造出的二叉树如下:
算法思路
1 构造
1.定义栈结构Stack<BTNode<Character>> stack
用于临时存储树节点
2.定义节点类型BTNode<Character> p
用于保存当前处理的节点
3.定义布尔值isLeft
判断当前处理的是哪个子树,true
为左子树,false
为右子树
4.以字符ch
的形式遍历str
:
4.1 当ch
为字母的时候,将ch
作为val
值新建节点,保存在p
中,判断根节点root == null
,若为true
,说明此时二叉树为空,直接将root
置为p
,否则取栈顶元素stack.peek()
,并判断布尔值isLeft
,若为true
,说明此时应该处理左子树,将栈顶元素的左子树置为p
,即stack.peek().left = p
,否则将其右子树置为p
4.2 当ch
为左括号(
时,说明即将处理p
的子树,将p
入栈,并将isLeft
置为true
4.3 当ch
为右括号)
时,说明当前节点的子树已处理完毕,栈顶元素出栈
4.4 当ch
为逗号,
时,说明左子树处理完毕,即将处理右子树,将isLeft
置为false
5.遍历完毕,结束
2 输出
1.定义字符串str
存储输出结果
2.判断root
是否为null
2.1 root
不为null
:
2.1.1 将root.val
加入str
中
2.1.2判断root
的左右子树是否至少有一个不为null
,若有一个不为null
,说明节点存在子树,此时str
中加入(
,并递归处理左右子树,在处理右子树前注意:判断右子树是否为null
,若不为null
,str
中应加入,
。左右子树处理完后,str
中加入)
2.2 root
为null
,直接返回str
代码
二叉树节点BTNode
class BTNode<T> {
T val;
BTNode<T> left;
BTNode<T> right;
public BTNode() {
this(null);
}
public BTNode(T val) {
this.val = val;
this.left = null;
this.right = null;
}
}
二叉树基本运算
class MyBTree {
BTNode<Character> root;
public MyBTree() {
root = null;
}
// 返回根节点
public BTNode<Character> getRoot() {
return this.root;
}
// 根据规范字符串建立二叉树
public void CreatTree(String str) {
Stack<BTNode<Character>> stack = new Stack<BTNode<Character>>();
BTNode<Character> p = null;
boolean isLeft = true;
for (char ch : str.toCharArray()) {
switch (ch) {
case '(':
stack.push(p);
isLeft = true;
break;
case ')':
stack.pop();
break;
case ',':
isLeft = false;
break;
default:
p = new BTNode<Character>(ch);
if (root == null) {
root = p;
} else {
if (isLeft) {
stack.peek().left = p;
} else {
stack.peek().right = p;
}
}
}
}
}
// 根据给定val值找到对应节点并返回
public BTNode<Character> getNode(BTNode<Character> root, char val) {
if (root == null) {
return null;
}
if (root.val == val) {
return root;
} else {
BTNode<Character> p = getNode(root.left, val);
if (p != null) {
return p;
} else {
return getNode(root.right, val);
}
}
}
// 获取二叉树最大深度
public int getDepth(BTNode<Character> root) {
return root == null ? 0 : Math.max(getDepth(root.left) + 1, getDepth(root.right) + 1);
}
// 格式化输出二叉树
public String toString(BTNode<Character> root) {
String str = "";
if (root != null) {
str += root.val;
if (root.left != null || root.right != null) {
str += "(";
str += toString(root.left);
if (root.right != null) {
str += ",";
}
str += toString(root.right);
str += ")";
}
}
return str;
}
}