利用括号表示串创建二叉树,并通过二叉树的中序遍历结果进行验证java
时间: 2024-01-23 14:16:59 浏览: 64
用java实现二叉树的创建和遍历.doc
好的,我可以帮你解答这个问题。
首先,我们需要定义一个二叉树节点的类:
```java
class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char x) { val = x; }
}
```
然后,我们可以通过递归的方式,根据括号表示串创建二叉树。具体实现如下:
```java
public static TreeNode createTree(String s) {
if (s == null || s.length() == 0) {
return null;
}
int i = 0;
while (i < s.length() && s.charAt(i) != '(') {
i++;
}
TreeNode root = new TreeNode(s.charAt(i - 1));
int j = i + 1, count = 0;
while (j < s.length() && (count > 0 || s.charAt(j) != ')')) {
if (s.charAt(j) == '(') {
count++;
} else if (s.charAt(j) == ')') {
count--;
}
j++;
}
root.left = createTree(s.substring(i, j + 1));
root.right = createTree(s.substring(j + 2, s.length() - 1));
return root;
}
```
最后,我们可以通过二叉树的中序遍历结果进行验证,具体实现如下:
```java
public static void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
inorderTraversal(root.left);
System.out.print(root.val + " ");
inorderTraversal(root.right);
}
public static boolean validate(String s, String inorder) {
TreeNode root = createTree(s);
StringBuilder sb = new StringBuilder();
inorderTraversal(root, sb);
return inorder.equals(sb.toString());
}
```
其中,`inorderTraversal` 方法用于进行中序遍历,并将遍历结果存储在 `StringBuilder` 中。
完整的实现代码如下:
```java
class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char x) { val = x; }
}
public class Main {
public static void main(String[] args) {
String s = "(A(B(D,E(G,)),C(,F)))";
String inorder = "DGBEAFC";
boolean isValid = validate(s, inorder);
System.out.println(isValid);
}
public static TreeNode createTree(String s) {
if (s == null || s.length() == 0) {
return null;
}
int i = 0;
while (i < s.length() && s.charAt(i) != '(') {
i++;
}
TreeNode root = new TreeNode(s.charAt(i - 1));
int j = i + 1, count = 0;
while (j < s.length() && (count > 0 || s.charAt(j) != ')')) {
if (s.charAt(j) == '(') {
count++;
} else if (s.charAt(j) == ')') {
count--;
}
j++;
}
root.left = createTree(s.substring(i, j + 1));
root.right = createTree(s.substring(j + 2, s.length() - 1));
return root;
}
public static void inorderTraversal(TreeNode root, StringBuilder sb) {
if (root == null) {
return;
}
inorderTraversal(root.left, sb);
sb.append(root.val);
inorderTraversal(root.right, sb);
}
public static boolean validate(String s, String inorder) {
TreeNode root = createTree(s);
StringBuilder sb = new StringBuilder();
inorderTraversal(root, sb);
return inorder.equals(sb.toString());
}
}
```
希望这个答案能够帮助到你!
阅读全文