// 递归
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else if (val > root.val) {
root.right = insertIntoBST(root.right, val);
}
return root;
}
// 迭代
public TreeNode insertIntoBST2(TreeNode root, int val) {
TreeNode p = root;
while (p != null) {
if (val > p.val) {
if (p.right == null) {
p.right = new TreeNode(val);
return root;
} else {
p = p.right;
}
} else if (val < p.val) {
if (p.left == null) {
p.left = new TreeNode(val);
return root;
} else {
p = p.left;
}
}
}
return root;
}
网友评论