java 实现 通过前序遍历的结果构建二叉树
时间: 2023-11-22 13:04:23 浏览: 42
可以通过递归的方式来实现通过前序遍历结果构建二叉树。下面是一个示例的 Java 代码:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class ConstructBinaryTree {
private int index = 0;
public TreeNode buildTree(int[] preorder) {
if (preorder == null || preorder.length == 0) {
return null;
}
return buildTree(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private TreeNode buildTree(int[] preorder, int min, int max) {
if (index >= preorder.length || preorder[index] < min || preorder[index] > max) {
return null;
}
TreeNode root = new TreeNode(preorder[index]);
index++;
root.left = buildTree(preorder, min, root.val);
root.right = buildTree(preorder, root.val, max);
return root;
}
}
```
你可以使用 `buildTree` 方法来构建二叉树,传入的参数是前序遍历结果的数组。这个方法内部会递归地构建左子树和右子树,并返回根节点。每次递归时,我们需要指定当前子树节点值的范围,确保左子树节点值小于当前节点值,右子树节点值大于当前节点值。
希望这个示例能帮助到你!如果有任何疑问,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)