利用括号表示串创建二叉树,并通过二叉树的中序遍历结果进行验证。java 实现
时间: 2024-01-23 09:16:27 浏览: 63
用java实现二叉树的创建和遍历.doc
好的,下面是用 Java 实现括号表示法创建二叉树,并通过中序遍历验证的代码:
```java
import java.util.*;
class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char val) {
this.val = val;
}
}
public class Main {
public static void main(String[] args) {
String s = "(A(B()())(C(D()())(E()())))";
TreeNode root = buildTree(s);
List<Character> inorder = inorderTraversal(root);
System.out.println(inorder.equals(Arrays.asList('B', 'A', 'D', 'C', 'E')));
}
public static TreeNode buildTree(String s) {
Stack<TreeNode> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(null);
} else if (c == ')') {
TreeNode right = stack.pop();
TreeNode left = stack.pop();
TreeNode node = new TreeNode(left.val);
node.left = left.left;
node.right = right;
stack.push(node);
} else {
stack.push(new TreeNode(c));
}
}
return stack.pop();
}
public static List<Character> inorderTraversal(TreeNode root) {
List<Character> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode node = stack.pop();
res.add(node.val);
root = node.right;
}
return res;
}
}
```
运行结果为`true`,说明括号表示法创建二叉树的方法是正确的。
阅读全文