# 二叉排序树的建立和遍历(java)

```class TreeNode{
int val;
TreeNode left;
TreeNode right;

TreeNode(){

}

TreeNode(int value){
this.val = value;
this.left = null;
this.right = null;
}

TreeNode(int value, TreeNode left, TreeNode right){
this.val = value;
this.left = left;
this.right = right;
}
}```

```public static TreeNode buildBST(int[] data){
//建立二叉排序树
//假设data中的数字是互不相同的
TreeNode root = new TreeNode(data[0]);
for(int i = 1; i < data.length; i++){
insert(root, data[i]);
}

return root;
}

private static TreeNode insert(TreeNode root, int value) {
//二叉排序树插入节点
if(root == null){
root = new TreeNode(value);
}else{
if(value <= root.val){
//插入到左子树
root.left = insert(root.left, value);
}else{
//插入到右子树
root.right = insert(root.right, value);
}
}

return root;
}```

```public static void preOrder(TreeNode root){
if(root == null){
return;
}
System.out.print(root.val + " ");
if(root.left != null){
preOrder(root.left);
}
if(root.right != null){
preOrder(root.right);
}
}```

main函数:

```public static void main(String[] args) {
int[] data = {3,1,2,5,0,7,9,8};
TreeNode root = Main.buildBST(data);
Main.preOrder(root);
}```

114 篇文章54 人订阅

0 条评论

## 相关文章

7630

### 85. 在二叉查找树中插入节点常规操作

You can assume there is no duplicate values in this tree + node.

25420

### 二叉查找树编码与解码

LeetCode 449 给定一个二叉查找树，实现对该二叉查找树编码与解码功能。编码即将二叉查找树转为字符串，解码即将字符串转为二叉查找树。不限制使用何种编码...

6510

8820

### Leetcode 103 Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' valu...

218100

### Leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree. Not...

20260

### Leetcode 101 Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric arou...

185100

18130

8510

### Leetcode 124 Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. For this problem, a path is de...

22290