leetcode题目地址
利用二叉搜索树性质插入。
时间复杂度:
O
(
H
)
O(H)
O(H)
空间复杂度:
O
(
n
)
O(n)
O(n)
递归
// java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void insert(TreeNode root, int val){
if(root == null) return;
if(val > root.val && root.right == null){
root.right = new TreeNode(val);
return;
}
if(val < root.val && root.left == null){
root.left = new TreeNode(val);
return;
}
if(val > root.val) insert(root.right, val);
if(val < root.val) insert(root.left, val);
}
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
insert(root, val);
return root;
}
}
迭代一
// java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode cur = root;
TreeNode parent = root;
while(cur != null){
parent = cur;
if(cur.val > val) cur = cur.left;
else cur = cur.right;
}
cur = new TreeNode(val);
if(val > parent.val) parent.right = cur;
else parent.left = cur;
return root;
}
}
迭代二
// java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode cur = root;
while(true){
if(cur.val > val) {
if(cur.left == null) {
cur.left = new TreeNode(val);
break;
}
cur = cur.left;
} else {
if(cur.right == null){
cur.right = new TreeNode(val);
break;
}
cur = cur.right;
}
}
return root;
}
}