链表方式构建二叉搜索树
Binary Search Tree
- 二叉树: 最多有两个子节点
- 左小右大; BST的特点

构建节点
节点构成
一般节点有三部分构成:
- 节点的数据 val
- 节点的左子节点 left
- 节点的右子节点 right
节点实现
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
添加节点(链表)
循环方式构建
- 如果无根节点,新节点就是根节点。
- 与节点的左、右节点值比较。
public void insert(int val) {
TreeNode newNode = new TreeNode(val);
if(root == null) {
root = newNode;
return;
}
TreeNode curr = root;
while (curr != null) {
if (val > curr.val) {
if (curr.right == null) {
curr.right = newNode;
return;
}
curr = curr.right;
} else {
if (curr.left == null) {
curr.left = newNode;
return;
}
curr = curr.left;
}
}
}
递归方式构建
public TreeNode insert(TreeNode root, int val) {
TreeNode newNode = new TreeNode(val);
if (root == null) {
root = newNode;
return root;
}
if (val > root.val) {
root.right = insert(root.right, val);
}
if (val < root.val) {
root.left = insert(root.left, val);
}
return root;
}

被折叠的 条评论
为什么被折叠?



